]> Sergey Matveev's repositories - btrtrc.git/blob - torrent.go
Combine pending and last requested
[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/slices"
27         "github.com/anacrolix/missinggo/v2"
28         "github.com/anacrolix/missinggo/v2/bitmap"
29         "github.com/anacrolix/missinggo/v2/pubsub"
30         "github.com/anacrolix/multiless"
31         "github.com/anacrolix/sync"
32         request_strategy "github.com/anacrolix/torrent/request-strategy"
33         typedRoaring "github.com/anacrolix/torrent/typed-roaring"
34         "github.com/davecgh/go-spew/spew"
35         "github.com/pion/datachannel"
36
37         "github.com/anacrolix/torrent/bencode"
38         "github.com/anacrolix/torrent/common"
39         "github.com/anacrolix/torrent/metainfo"
40         pp "github.com/anacrolix/torrent/peer_protocol"
41         "github.com/anacrolix/torrent/segments"
42         "github.com/anacrolix/torrent/storage"
43         "github.com/anacrolix/torrent/tracker"
44         "github.com/anacrolix/torrent/webseed"
45         "github.com/anacrolix/torrent/webtorrent"
46 )
47
48 // Maintains state of torrent within a Client. Many methods should not be called before the info is
49 // available, see .Info and .GotInfo.
50 type Torrent struct {
51         // Torrent-level aggregate statistics. First in struct to ensure 64-bit
52         // alignment. See #262.
53         stats  ConnStats
54         cl     *Client
55         logger log.Logger
56
57         networkingEnabled      chansync.Flag
58         dataDownloadDisallowed chansync.Flag
59         dataUploadDisallowed   bool
60         userOnWriteChunkErr    func(error)
61
62         closed   chansync.SetOnce
63         infoHash metainfo.Hash
64         pieces   []Piece
65         // Values are the piece indices that changed.
66         pieceStateChanges pubsub.PubSub[PieceStateChange]
67         // The size of chunks to request from peers over the wire. This is
68         // normally 16KiB by convention these days.
69         chunkSize pp.Integer
70         chunkPool sync.Pool
71         // Total length of the torrent in bytes. Stored because it's not O(1) to
72         // get this from the info dict.
73         length *int64
74
75         // The storage to open when the info dict becomes available.
76         storageOpener *storage.Client
77         // Storage for torrent data.
78         storage *storage.Torrent
79         // Read-locked for using storage, and write-locked for Closing.
80         storageLock sync.RWMutex
81
82         // TODO: Only announce stuff is used?
83         metainfo metainfo.MetaInfo
84
85         // The info dict. nil if we don't have it (yet).
86         info      *metainfo.Info
87         fileIndex segments.Index
88         files     *[]*File
89
90         webSeeds map[string]*Peer
91         // Active peer connections, running message stream loops. TODO: Make this
92         // open (not-closed) connections only.
93         conns               map[*PeerConn]struct{}
94         maxEstablishedConns int
95         // Set of addrs to which we're attempting to connect. Connections are
96         // half-open until all handshakes are completed.
97         halfOpen map[string]PeerInfo
98
99         // Reserve of peers to connect to. A peer can be both here and in the
100         // active connections if were told about the peer after connecting with
101         // them. That encourages us to reconnect to peers that are well known in
102         // the swarm.
103         peers prioritizedPeers
104         // Whether we want to know to know more peers.
105         wantPeersEvent missinggo.Event
106         // An announcer for each tracker URL.
107         trackerAnnouncers map[string]torrentTrackerAnnouncer
108         // How many times we've initiated a DHT announce. TODO: Move into stats.
109         numDHTAnnounces int
110
111         // Name used if the info name isn't available. Should be cleared when the
112         // Info does become available.
113         nameMu      sync.RWMutex
114         displayName string
115
116         // The bencoded bytes of the info dict. This is actively manipulated if
117         // the info bytes aren't initially available, and we try to fetch them
118         // from peers.
119         metadataBytes []byte
120         // Each element corresponds to the 16KiB metadata pieces. If true, we have
121         // received that piece.
122         metadataCompletedChunks []bool
123         metadataChanged         sync.Cond
124
125         // Closed when .Info is obtained.
126         gotMetainfoC chan struct{}
127
128         readers                map[*reader]struct{}
129         _readerNowPieces       bitmap.Bitmap
130         _readerReadaheadPieces bitmap.Bitmap
131
132         // A cache of pieces we need to get. Calculated from various piece and
133         // file priorities and completion states elsewhere.
134         _pendingPieces roaring.Bitmap
135         // A cache of completed piece indices.
136         _completedPieces roaring.Bitmap
137         // Pieces that need to be hashed.
138         piecesQueuedForHash       bitmap.Bitmap
139         activePieceHashes         int
140         initialPieceCheckDisabled bool
141
142         connsWithAllPieces map[*Peer]struct{}
143
144         requestState map[RequestIndex]requestState
145         // Chunks we've written to since the corresponding piece was last checked.
146         dirtyChunks typedRoaring.Bitmap[RequestIndex]
147
148         pex pexState
149
150         // Is On when all pieces are complete.
151         Complete chansync.Flag
152
153         // Torrent sources in use keyed by the source string.
154         activeSources sync.Map
155         sourcesLogger log.Logger
156
157         smartBanCache smartBanCache
158 }
159
160 func (t *Torrent) selectivePieceAvailabilityFromPeers(i pieceIndex) (count int) {
161         // This could be done with roaring.BitSliceIndexing.
162         t.iterPeers(func(peer *Peer) {
163                 if _, ok := t.connsWithAllPieces[peer]; ok {
164                         return
165                 }
166                 if peer.peerHasPiece(i) {
167                         count++
168                 }
169         })
170         return
171 }
172
173 func (t *Torrent) decPieceAvailability(i pieceIndex) {
174         if !t.haveInfo() {
175                 return
176         }
177         p := t.piece(i)
178         if p.relativeAvailability <= 0 {
179                 panic(p.relativeAvailability)
180         }
181         p.relativeAvailability--
182         t.updatePieceRequestOrder(i)
183 }
184
185 func (t *Torrent) incPieceAvailability(i pieceIndex) {
186         // If we don't the info, this should be reconciled when we do.
187         if t.haveInfo() {
188                 p := t.piece(i)
189                 p.relativeAvailability++
190                 t.updatePieceRequestOrder(i)
191         }
192 }
193
194 func (t *Torrent) readerNowPieces() bitmap.Bitmap {
195         return t._readerNowPieces
196 }
197
198 func (t *Torrent) readerReadaheadPieces() bitmap.Bitmap {
199         return t._readerReadaheadPieces
200 }
201
202 func (t *Torrent) ignorePieceForRequests(i pieceIndex) bool {
203         return !t.wantPieceIndex(i)
204 }
205
206 // Returns a channel that is closed when the Torrent is closed.
207 func (t *Torrent) Closed() events.Done {
208         return t.closed.Done()
209 }
210
211 // KnownSwarm returns the known subset of the peers in the Torrent's swarm, including active,
212 // pending, and half-open peers.
213 func (t *Torrent) KnownSwarm() (ks []PeerInfo) {
214         // Add pending peers to the list
215         t.peers.Each(func(peer PeerInfo) {
216                 ks = append(ks, peer)
217         })
218
219         // Add half-open peers to the list
220         for _, peer := range t.halfOpen {
221                 ks = append(ks, peer)
222         }
223
224         // Add active peers to the list
225         for conn := range t.conns {
226                 ks = append(ks, PeerInfo{
227                         Id:     conn.PeerID,
228                         Addr:   conn.RemoteAddr,
229                         Source: conn.Discovery,
230                         // > If the connection is encrypted, that's certainly enough to set SupportsEncryption.
231                         // > But if we're not connected to them with an encrypted connection, I couldn't say
232                         // > what's appropriate. We can carry forward the SupportsEncryption value as we
233                         // > received it from trackers/DHT/PEX, or just use the encryption state for the
234                         // > connection. It's probably easiest to do the latter for now.
235                         // https://github.com/anacrolix/torrent/pull/188
236                         SupportsEncryption: conn.headerEncrypted,
237                 })
238         }
239
240         return
241 }
242
243 func (t *Torrent) setChunkSize(size pp.Integer) {
244         t.chunkSize = size
245         t.chunkPool = sync.Pool{
246                 New: func() interface{} {
247                         b := make([]byte, size)
248                         return &b
249                 },
250         }
251 }
252
253 func (t *Torrent) pieceComplete(piece pieceIndex) bool {
254         return t._completedPieces.Contains(bitmap.BitIndex(piece))
255 }
256
257 func (t *Torrent) pieceCompleteUncached(piece pieceIndex) storage.Completion {
258         if t.storage == nil {
259                 return storage.Completion{Complete: false, Ok: true}
260         }
261         return t.pieces[piece].Storage().Completion()
262 }
263
264 // There's a connection to that address already.
265 func (t *Torrent) addrActive(addr string) bool {
266         if _, ok := t.halfOpen[addr]; ok {
267                 return true
268         }
269         for c := range t.conns {
270                 ra := c.RemoteAddr
271                 if ra.String() == addr {
272                         return true
273                 }
274         }
275         return false
276 }
277
278 func (t *Torrent) appendUnclosedConns(ret []*PeerConn) []*PeerConn {
279         return t.appendConns(ret, func(conn *PeerConn) bool {
280                 return !conn.closed.IsSet()
281         })
282 }
283
284 func (t *Torrent) appendConns(ret []*PeerConn, f func(*PeerConn) bool) []*PeerConn {
285         for c := range t.conns {
286                 if f(c) {
287                         ret = append(ret, c)
288                 }
289         }
290         return ret
291 }
292
293 func (t *Torrent) addPeer(p PeerInfo) (added bool) {
294         cl := t.cl
295         torrent.Add(fmt.Sprintf("peers added by source %q", p.Source), 1)
296         if t.closed.IsSet() {
297                 return false
298         }
299         if ipAddr, ok := tryIpPortFromNetAddr(p.Addr); ok {
300                 if cl.badPeerIPPort(ipAddr.IP, ipAddr.Port) {
301                         torrent.Add("peers not added because of bad addr", 1)
302                         // cl.logger.Printf("peers not added because of bad addr: %v", p)
303                         return false
304                 }
305         }
306         if replaced, ok := t.peers.AddReturningReplacedPeer(p); ok {
307                 torrent.Add("peers replaced", 1)
308                 if !replaced.equal(p) {
309                         t.logger.WithDefaultLevel(log.Debug).Printf("added %v replacing %v", p, replaced)
310                         added = true
311                 }
312         } else {
313                 added = true
314         }
315         t.openNewConns()
316         for t.peers.Len() > cl.config.TorrentPeersHighWater {
317                 _, ok := t.peers.DeleteMin()
318                 if ok {
319                         torrent.Add("excess reserve peers discarded", 1)
320                 }
321         }
322         return
323 }
324
325 func (t *Torrent) invalidateMetadata() {
326         for i := 0; i < len(t.metadataCompletedChunks); i++ {
327                 t.metadataCompletedChunks[i] = false
328         }
329         t.nameMu.Lock()
330         t.gotMetainfoC = make(chan struct{})
331         t.info = nil
332         t.nameMu.Unlock()
333 }
334
335 func (t *Torrent) saveMetadataPiece(index int, data []byte) {
336         if t.haveInfo() {
337                 return
338         }
339         if index >= len(t.metadataCompletedChunks) {
340                 t.logger.Printf("%s: ignoring metadata piece %d", t, index)
341                 return
342         }
343         copy(t.metadataBytes[(1<<14)*index:], data)
344         t.metadataCompletedChunks[index] = true
345 }
346
347 func (t *Torrent) metadataPieceCount() int {
348         return (len(t.metadataBytes) + (1 << 14) - 1) / (1 << 14)
349 }
350
351 func (t *Torrent) haveMetadataPiece(piece int) bool {
352         if t.haveInfo() {
353                 return (1<<14)*piece < len(t.metadataBytes)
354         } else {
355                 return piece < len(t.metadataCompletedChunks) && t.metadataCompletedChunks[piece]
356         }
357 }
358
359 func (t *Torrent) metadataSize() int {
360         return len(t.metadataBytes)
361 }
362
363 func infoPieceHashes(info *metainfo.Info) (ret [][]byte) {
364         for i := 0; i < len(info.Pieces); i += sha1.Size {
365                 ret = append(ret, info.Pieces[i:i+sha1.Size])
366         }
367         return
368 }
369
370 func (t *Torrent) makePieces() {
371         hashes := infoPieceHashes(t.info)
372         t.pieces = make([]Piece, len(hashes))
373         for i, hash := range hashes {
374                 piece := &t.pieces[i]
375                 piece.t = t
376                 piece.index = pieceIndex(i)
377                 piece.noPendingWrites.L = &piece.pendingWritesMutex
378                 piece.hash = (*metainfo.Hash)(unsafe.Pointer(&hash[0]))
379                 files := *t.files
380                 beginFile := pieceFirstFileIndex(piece.torrentBeginOffset(), files)
381                 endFile := pieceEndFileIndex(piece.torrentEndOffset(), files)
382                 piece.files = files[beginFile:endFile]
383                 piece.undirtiedChunksIter = undirtiedChunksIter{
384                         TorrentDirtyChunks: &t.dirtyChunks,
385                         StartRequestIndex:  piece.requestIndexOffset(),
386                         EndRequestIndex:    piece.requestIndexOffset() + piece.numChunks(),
387                 }
388         }
389 }
390
391 // Returns the index of the first file containing the piece. files must be
392 // ordered by offset.
393 func pieceFirstFileIndex(pieceOffset int64, files []*File) int {
394         for i, f := range files {
395                 if f.offset+f.length > pieceOffset {
396                         return i
397                 }
398         }
399         return 0
400 }
401
402 // Returns the index after the last file containing the piece. files must be
403 // ordered by offset.
404 func pieceEndFileIndex(pieceEndOffset int64, files []*File) int {
405         for i, f := range files {
406                 if f.offset+f.length >= pieceEndOffset {
407                         return i + 1
408                 }
409         }
410         return 0
411 }
412
413 func (t *Torrent) cacheLength() {
414         var l int64
415         for _, f := range t.info.UpvertedFiles() {
416                 l += f.Length
417         }
418         t.length = &l
419 }
420
421 // TODO: This shouldn't fail for storage reasons. Instead we should handle storage failure
422 // separately.
423 func (t *Torrent) setInfo(info *metainfo.Info) error {
424         if err := validateInfo(info); err != nil {
425                 return fmt.Errorf("bad info: %s", err)
426         }
427         if t.storageOpener != nil {
428                 var err error
429                 t.storage, err = t.storageOpener.OpenTorrent(info, t.infoHash)
430                 if err != nil {
431                         return fmt.Errorf("error opening torrent storage: %s", err)
432                 }
433         }
434         t.nameMu.Lock()
435         t.info = info
436         t.nameMu.Unlock()
437         t.updateComplete()
438         t.fileIndex = segments.NewIndex(common.LengthIterFromUpvertedFiles(info.UpvertedFiles()))
439         t.displayName = "" // Save a few bytes lol.
440         t.initFiles()
441         t.cacheLength()
442         t.makePieces()
443         return nil
444 }
445
446 func (t *Torrent) pieceRequestOrderKey(i int) request_strategy.PieceRequestOrderKey {
447         return request_strategy.PieceRequestOrderKey{
448                 InfoHash: t.infoHash,
449                 Index:    i,
450         }
451 }
452
453 // This seems to be all the follow-up tasks after info is set, that can't fail.
454 func (t *Torrent) onSetInfo() {
455         t.initPieceRequestOrder()
456         for i := range t.pieces {
457                 p := &t.pieces[i]
458                 // Need to add relativeAvailability before updating piece completion, as that may result in conns
459                 // being dropped.
460                 if p.relativeAvailability != 0 {
461                         panic(p.relativeAvailability)
462                 }
463                 p.relativeAvailability = t.selectivePieceAvailabilityFromPeers(i)
464                 t.addRequestOrderPiece(i)
465                 t.updatePieceCompletion(i)
466                 if !t.initialPieceCheckDisabled && !p.storageCompletionOk {
467                         // t.logger.Printf("piece %s completion unknown, queueing check", p)
468                         t.queuePieceCheck(i)
469                 }
470         }
471         t.cl.event.Broadcast()
472         close(t.gotMetainfoC)
473         t.updateWantPeersEvent()
474         t.requestState = make(map[RequestIndex]requestState)
475         t.tryCreateMorePieceHashers()
476         t.iterPeers(func(p *Peer) {
477                 p.onGotInfo(t.info)
478                 p.updateRequests("onSetInfo")
479         })
480 }
481
482 // Called when metadata for a torrent becomes available.
483 func (t *Torrent) setInfoBytesLocked(b []byte) error {
484         if metainfo.HashBytes(b) != t.infoHash {
485                 return errors.New("info bytes have wrong hash")
486         }
487         var info metainfo.Info
488         if err := bencode.Unmarshal(b, &info); err != nil {
489                 return fmt.Errorf("error unmarshalling info bytes: %s", err)
490         }
491         t.metadataBytes = b
492         t.metadataCompletedChunks = nil
493         if t.info != nil {
494                 return nil
495         }
496         if err := t.setInfo(&info); err != nil {
497                 return err
498         }
499         t.onSetInfo()
500         return nil
501 }
502
503 func (t *Torrent) haveAllMetadataPieces() bool {
504         if t.haveInfo() {
505                 return true
506         }
507         if t.metadataCompletedChunks == nil {
508                 return false
509         }
510         for _, have := range t.metadataCompletedChunks {
511                 if !have {
512                         return false
513                 }
514         }
515         return true
516 }
517
518 // TODO: Propagate errors to disconnect peer.
519 func (t *Torrent) setMetadataSize(size int) (err error) {
520         if t.haveInfo() {
521                 // We already know the correct metadata size.
522                 return
523         }
524         if uint32(size) > maxMetadataSize {
525                 return errors.New("bad size")
526         }
527         if len(t.metadataBytes) == size {
528                 return
529         }
530         t.metadataBytes = make([]byte, size)
531         t.metadataCompletedChunks = make([]bool, (size+(1<<14)-1)/(1<<14))
532         t.metadataChanged.Broadcast()
533         for c := range t.conns {
534                 c.requestPendingMetadata()
535         }
536         return
537 }
538
539 // The current working name for the torrent. Either the name in the info dict,
540 // or a display name given such as by the dn value in a magnet link, or "".
541 func (t *Torrent) name() string {
542         t.nameMu.RLock()
543         defer t.nameMu.RUnlock()
544         if t.haveInfo() {
545                 return t.info.BestName()
546         }
547         if t.displayName != "" {
548                 return t.displayName
549         }
550         return "infohash:" + t.infoHash.HexString()
551 }
552
553 func (t *Torrent) pieceState(index pieceIndex) (ret PieceState) {
554         p := &t.pieces[index]
555         ret.Priority = t.piecePriority(index)
556         ret.Completion = p.completion()
557         ret.QueuedForHash = p.queuedForHash()
558         ret.Hashing = p.hashing
559         ret.Checking = ret.QueuedForHash || ret.Hashing
560         ret.Marking = p.marking
561         if !ret.Complete && t.piecePartiallyDownloaded(index) {
562                 ret.Partial = true
563         }
564         return
565 }
566
567 func (t *Torrent) metadataPieceSize(piece int) int {
568         return metadataPieceSize(len(t.metadataBytes), piece)
569 }
570
571 func (t *Torrent) newMetadataExtensionMessage(c *PeerConn, msgType pp.ExtendedMetadataRequestMsgType, piece int, data []byte) pp.Message {
572         return pp.Message{
573                 Type:       pp.Extended,
574                 ExtendedID: c.PeerExtensionIDs[pp.ExtensionNameMetadata],
575                 ExtendedPayload: append(bencode.MustMarshal(pp.ExtendedMetadataRequestMsg{
576                         Piece:     piece,
577                         TotalSize: len(t.metadataBytes),
578                         Type:      msgType,
579                 }), data...),
580         }
581 }
582
583 type pieceAvailabilityRun struct {
584         Count        pieceIndex
585         Availability int
586 }
587
588 func (me pieceAvailabilityRun) String() string {
589         return fmt.Sprintf("%v(%v)", me.Count, me.Availability)
590 }
591
592 func (t *Torrent) pieceAvailabilityRuns() (ret []pieceAvailabilityRun) {
593         rle := missinggo.NewRunLengthEncoder(func(el interface{}, count uint64) {
594                 ret = append(ret, pieceAvailabilityRun{Availability: el.(int), Count: int(count)})
595         })
596         for i := range t.pieces {
597                 rle.Append(t.pieces[i].availability(), 1)
598         }
599         rle.Flush()
600         return
601 }
602
603 func (t *Torrent) pieceAvailabilityFrequencies() (freqs []int) {
604         freqs = make([]int, t.numActivePeers()+1)
605         for i := range t.pieces {
606                 freqs[t.piece(i).availability()]++
607         }
608         return
609 }
610
611 func (t *Torrent) pieceStateRuns() (ret PieceStateRuns) {
612         rle := missinggo.NewRunLengthEncoder(func(el interface{}, count uint64) {
613                 ret = append(ret, PieceStateRun{
614                         PieceState: el.(PieceState),
615                         Length:     int(count),
616                 })
617         })
618         for index := range t.pieces {
619                 rle.Append(t.pieceState(pieceIndex(index)), 1)
620         }
621         rle.Flush()
622         return
623 }
624
625 // Produces a small string representing a PieceStateRun.
626 func (psr PieceStateRun) String() (ret string) {
627         ret = fmt.Sprintf("%d", psr.Length)
628         ret += func() string {
629                 switch psr.Priority {
630                 case PiecePriorityNext:
631                         return "N"
632                 case PiecePriorityNormal:
633                         return "."
634                 case PiecePriorityReadahead:
635                         return "R"
636                 case PiecePriorityNow:
637                         return "!"
638                 case PiecePriorityHigh:
639                         return "H"
640                 default:
641                         return ""
642                 }
643         }()
644         if psr.Hashing {
645                 ret += "H"
646         }
647         if psr.QueuedForHash {
648                 ret += "Q"
649         }
650         if psr.Marking {
651                 ret += "M"
652         }
653         if psr.Partial {
654                 ret += "P"
655         }
656         if psr.Complete {
657                 ret += "C"
658         }
659         if !psr.Ok {
660                 ret += "?"
661         }
662         return
663 }
664
665 func (t *Torrent) writeStatus(w io.Writer) {
666         fmt.Fprintf(w, "Infohash: %s\n", t.infoHash.HexString())
667         fmt.Fprintf(w, "Metadata length: %d\n", t.metadataSize())
668         if !t.haveInfo() {
669                 fmt.Fprintf(w, "Metadata have: ")
670                 for _, h := range t.metadataCompletedChunks {
671                         fmt.Fprintf(w, "%c", func() rune {
672                                 if h {
673                                         return 'H'
674                                 } else {
675                                         return '.'
676                                 }
677                         }())
678                 }
679                 fmt.Fprintln(w)
680         }
681         fmt.Fprintf(w, "Piece length: %s\n",
682                 func() string {
683                         if t.haveInfo() {
684                                 return fmt.Sprintf("%v (%v chunks)",
685                                         t.usualPieceSize(),
686                                         float64(t.usualPieceSize())/float64(t.chunkSize))
687                         } else {
688                                 return "no info"
689                         }
690                 }(),
691         )
692         if t.info != nil {
693                 fmt.Fprintf(w, "Num Pieces: %d (%d completed)\n", t.numPieces(), t.numPiecesCompleted())
694                 fmt.Fprintf(w, "Piece States: %s\n", t.pieceStateRuns())
695                 // Generates a huge, unhelpful listing when piece availability is very scattered. Prefer
696                 // availability frequencies instead.
697                 if false {
698                         fmt.Fprintf(w, "Piece availability: %v\n", strings.Join(func() (ret []string) {
699                                 for _, run := range t.pieceAvailabilityRuns() {
700                                         ret = append(ret, run.String())
701                                 }
702                                 return
703                         }(), " "))
704                 }
705                 fmt.Fprintf(w, "Piece availability frequency: %v\n", strings.Join(
706                         func() (ret []string) {
707                                 for avail, freq := range t.pieceAvailabilityFrequencies() {
708                                         if freq == 0 {
709                                                 continue
710                                         }
711                                         ret = append(ret, fmt.Sprintf("%v: %v", avail, freq))
712                                 }
713                                 return
714                         }(),
715                         ", "))
716         }
717         fmt.Fprintf(w, "Reader Pieces:")
718         t.forReaderOffsetPieces(func(begin, end pieceIndex) (again bool) {
719                 fmt.Fprintf(w, " %d:%d", begin, end)
720                 return true
721         })
722         fmt.Fprintln(w)
723
724         fmt.Fprintf(w, "Enabled trackers:\n")
725         func() {
726                 tw := tabwriter.NewWriter(w, 0, 0, 2, ' ', 0)
727                 fmt.Fprintf(tw, "    URL\tExtra\n")
728                 for _, ta := range slices.Sort(slices.FromMapElems(t.trackerAnnouncers), func(l, r torrentTrackerAnnouncer) bool {
729                         lu := l.URL()
730                         ru := r.URL()
731                         var luns, runs url.URL = *lu, *ru
732                         luns.Scheme = ""
733                         runs.Scheme = ""
734                         var ml missinggo.MultiLess
735                         ml.StrictNext(luns.String() == runs.String(), luns.String() < runs.String())
736                         ml.StrictNext(lu.String() == ru.String(), lu.String() < ru.String())
737                         return ml.Less()
738                 }).([]torrentTrackerAnnouncer) {
739                         fmt.Fprintf(tw, "    %q\t%v\n", ta.URL(), ta.statusLine())
740                 }
741                 tw.Flush()
742         }()
743
744         fmt.Fprintf(w, "DHT Announces: %d\n", t.numDHTAnnounces)
745
746         spew.NewDefaultConfig()
747         spew.Fdump(w, t.statsLocked())
748
749         peers := t.peersAsSlice()
750         sort.Slice(peers, func(_i, _j int) bool {
751                 i := peers[_i]
752                 j := peers[_j]
753                 if less, ok := multiless.New().EagerSameLess(
754                         i.downloadRate() == j.downloadRate(), i.downloadRate() < j.downloadRate(),
755                 ).LessOk(); ok {
756                         return less
757                 }
758                 return worseConn(i, j)
759         })
760         for i, c := range peers {
761                 fmt.Fprintf(w, "%2d. ", i+1)
762                 c.writeStatus(w, t)
763         }
764 }
765
766 func (t *Torrent) haveInfo() bool {
767         return t.info != nil
768 }
769
770 // Returns a run-time generated MetaInfo that includes the info bytes and
771 // announce-list as currently known to the client.
772 func (t *Torrent) newMetaInfo() metainfo.MetaInfo {
773         return metainfo.MetaInfo{
774                 CreationDate: time.Now().Unix(),
775                 Comment:      "dynamic metainfo from client",
776                 CreatedBy:    "go.torrent",
777                 AnnounceList: t.metainfo.UpvertedAnnounceList().Clone(),
778                 InfoBytes: func() []byte {
779                         if t.haveInfo() {
780                                 return t.metadataBytes
781                         } else {
782                                 return nil
783                         }
784                 }(),
785                 UrlList: func() []string {
786                         ret := make([]string, 0, len(t.webSeeds))
787                         for url := range t.webSeeds {
788                                 ret = append(ret, url)
789                         }
790                         return ret
791                 }(),
792         }
793 }
794
795 // Get bytes left
796 func (t *Torrent) BytesMissing() (n int64) {
797         t.cl.rLock()
798         n = t.bytesMissingLocked()
799         t.cl.rUnlock()
800         return
801 }
802
803 func (t *Torrent) bytesMissingLocked() int64 {
804         return t.bytesLeft()
805 }
806
807 func iterFlipped(b *roaring.Bitmap, end uint64, cb func(uint32) bool) {
808         roaring.Flip(b, 0, end).Iterate(cb)
809 }
810
811 func (t *Torrent) bytesLeft() (left int64) {
812         iterFlipped(&t._completedPieces, uint64(t.numPieces()), func(x uint32) bool {
813                 p := t.piece(pieceIndex(x))
814                 left += int64(p.length() - p.numDirtyBytes())
815                 return true
816         })
817         return
818 }
819
820 // Bytes left to give in tracker announces.
821 func (t *Torrent) bytesLeftAnnounce() int64 {
822         if t.haveInfo() {
823                 return t.bytesLeft()
824         } else {
825                 return -1
826         }
827 }
828
829 func (t *Torrent) piecePartiallyDownloaded(piece pieceIndex) bool {
830         if t.pieceComplete(piece) {
831                 return false
832         }
833         if t.pieceAllDirty(piece) {
834                 return false
835         }
836         return t.pieces[piece].hasDirtyChunks()
837 }
838
839 func (t *Torrent) usualPieceSize() int {
840         return int(t.info.PieceLength)
841 }
842
843 func (t *Torrent) numPieces() pieceIndex {
844         return pieceIndex(t.info.NumPieces())
845 }
846
847 func (t *Torrent) numPiecesCompleted() (num pieceIndex) {
848         return pieceIndex(t._completedPieces.GetCardinality())
849 }
850
851 func (t *Torrent) close(wg *sync.WaitGroup) (err error) {
852         if !t.closed.Set() {
853                 err = errors.New("already closed")
854                 return
855         }
856         if t.storage != nil {
857                 wg.Add(1)
858                 go func() {
859                         defer wg.Done()
860                         t.storageLock.Lock()
861                         defer t.storageLock.Unlock()
862                         if f := t.storage.Close; f != nil {
863                                 err1 := f()
864                                 if err1 != nil {
865                                         t.logger.WithDefaultLevel(log.Warning).Printf("error closing storage: %v", err1)
866                                 }
867                         }
868                 }()
869         }
870         t.iterPeers(func(p *Peer) {
871                 p.close()
872         })
873         if t.storage != nil {
874                 t.deletePieceRequestOrder()
875         }
876         for i := range t.pieces {
877                 p := t.piece(i)
878                 if p.relativeAvailability != 0 {
879                         panic(fmt.Sprintf("piece %v has relative availability %v", i, p.relativeAvailability))
880                 }
881         }
882         t.pex.Reset()
883         t.cl.event.Broadcast()
884         t.pieceStateChanges.Close()
885         t.updateWantPeersEvent()
886         return
887 }
888
889 func (t *Torrent) requestOffset(r Request) int64 {
890         return torrentRequestOffset(*t.length, int64(t.usualPieceSize()), r)
891 }
892
893 // Return the request that would include the given offset into the torrent data. Returns !ok if
894 // there is no such request.
895 func (t *Torrent) offsetRequest(off int64) (req Request, ok bool) {
896         return torrentOffsetRequest(*t.length, t.info.PieceLength, int64(t.chunkSize), off)
897 }
898
899 func (t *Torrent) writeChunk(piece int, begin int64, data []byte) (err error) {
900         defer perf.ScopeTimerErr(&err)()
901         n, err := t.pieces[piece].Storage().WriteAt(data, begin)
902         if err == nil && n != len(data) {
903                 err = io.ErrShortWrite
904         }
905         return err
906 }
907
908 func (t *Torrent) bitfield() (bf []bool) {
909         bf = make([]bool, t.numPieces())
910         t._completedPieces.Iterate(func(piece uint32) (again bool) {
911                 bf[piece] = true
912                 return true
913         })
914         return
915 }
916
917 func (t *Torrent) pieceNumChunks(piece pieceIndex) chunkIndexType {
918         return chunkIndexType((t.pieceLength(piece) + t.chunkSize - 1) / t.chunkSize)
919 }
920
921 func (t *Torrent) chunksPerRegularPiece() chunkIndexType {
922         return chunkIndexType((pp.Integer(t.usualPieceSize()) + t.chunkSize - 1) / t.chunkSize)
923 }
924
925 func (t *Torrent) numRequests() RequestIndex {
926         if t.numPieces() == 0 {
927                 return 0
928         }
929         return RequestIndex(t.numPieces()-1)*t.chunksPerRegularPiece() + t.pieceNumChunks(t.numPieces()-1)
930 }
931
932 func (t *Torrent) pendAllChunkSpecs(pieceIndex pieceIndex) {
933         t.dirtyChunks.RemoveRange(
934                 uint64(t.pieceRequestIndexOffset(pieceIndex)),
935                 uint64(t.pieceRequestIndexOffset(pieceIndex+1)))
936 }
937
938 func (t *Torrent) pieceLength(piece pieceIndex) pp.Integer {
939         if t.info.PieceLength == 0 {
940                 // There will be no variance amongst pieces. Only pain.
941                 return 0
942         }
943         if piece == t.numPieces()-1 {
944                 ret := pp.Integer(*t.length % t.info.PieceLength)
945                 if ret != 0 {
946                         return ret
947                 }
948         }
949         return pp.Integer(t.info.PieceLength)
950 }
951
952 func (t *Torrent) smartBanBlockCheckingWriter(piece pieceIndex) *blockCheckingWriter {
953         return &blockCheckingWriter{
954                 cache:        &t.smartBanCache,
955                 requestIndex: t.pieceRequestIndexOffset(piece),
956                 chunkSize:    t.chunkSize.Int(),
957         }
958 }
959
960 func (t *Torrent) hashPiece(piece pieceIndex) (
961         ret metainfo.Hash,
962         // These are peers that sent us blocks that differ from what we hash here.
963         differingPeers map[bannableAddr]struct{},
964         err error,
965 ) {
966         p := t.piece(piece)
967         p.waitNoPendingWrites()
968         storagePiece := t.pieces[piece].Storage()
969
970         // Does the backend want to do its own hashing?
971         if i, ok := storagePiece.PieceImpl.(storage.SelfHashing); ok {
972                 var sum metainfo.Hash
973                 // log.Printf("A piece decided to self-hash: %d", piece)
974                 sum, err = i.SelfHash()
975                 missinggo.CopyExact(&ret, sum)
976                 return
977         }
978
979         hash := pieceHash.New()
980         const logPieceContents = false
981         smartBanWriter := t.smartBanBlockCheckingWriter(piece)
982         writers := []io.Writer{hash, smartBanWriter}
983         var examineBuf bytes.Buffer
984         if logPieceContents {
985                 writers = append(writers, &examineBuf)
986         }
987         _, err = storagePiece.WriteTo(io.MultiWriter(writers...))
988         if logPieceContents {
989                 t.logger.WithDefaultLevel(log.Debug).Printf("hashed %q with copy err %v", examineBuf.Bytes(), err)
990         }
991         smartBanWriter.Flush()
992         differingPeers = smartBanWriter.badPeers
993         missinggo.CopyExact(&ret, hash.Sum(nil))
994         return
995 }
996
997 func (t *Torrent) haveAnyPieces() bool {
998         return !t._completedPieces.IsEmpty()
999 }
1000
1001 func (t *Torrent) haveAllPieces() bool {
1002         if !t.haveInfo() {
1003                 return false
1004         }
1005         return t._completedPieces.GetCardinality() == bitmap.BitRange(t.numPieces())
1006 }
1007
1008 func (t *Torrent) havePiece(index pieceIndex) bool {
1009         return t.haveInfo() && t.pieceComplete(index)
1010 }
1011
1012 func (t *Torrent) maybeDropMutuallyCompletePeer(
1013         // I'm not sure about taking peer here, not all peer implementations actually drop. Maybe that's
1014         // okay?
1015         p *Peer,
1016 ) {
1017         if !t.cl.config.DropMutuallyCompletePeers {
1018                 return
1019         }
1020         if !t.haveAllPieces() {
1021                 return
1022         }
1023         if all, known := p.peerHasAllPieces(); !(known && all) {
1024                 return
1025         }
1026         if p.useful() {
1027                 return
1028         }
1029         t.logger.WithDefaultLevel(log.Debug).Printf("dropping %v, which is mutually complete", p)
1030         p.drop()
1031 }
1032
1033 func (t *Torrent) haveChunk(r Request) (ret bool) {
1034         // defer func() {
1035         //      log.Println("have chunk", r, ret)
1036         // }()
1037         if !t.haveInfo() {
1038                 return false
1039         }
1040         if t.pieceComplete(pieceIndex(r.Index)) {
1041                 return true
1042         }
1043         p := &t.pieces[r.Index]
1044         return !p.pendingChunk(r.ChunkSpec, t.chunkSize)
1045 }
1046
1047 func chunkIndexFromChunkSpec(cs ChunkSpec, chunkSize pp.Integer) chunkIndexType {
1048         return chunkIndexType(cs.Begin / chunkSize)
1049 }
1050
1051 func (t *Torrent) wantPieceIndex(index pieceIndex) bool {
1052         return t._pendingPieces.Contains(uint32(index))
1053 }
1054
1055 // A pool of []*PeerConn, to reduce allocations in functions that need to index or sort Torrent
1056 // conns (which is a map).
1057 var peerConnSlices sync.Pool
1058
1059 func getPeerConnSlice(cap int) []*PeerConn {
1060         getInterface := peerConnSlices.Get()
1061         if getInterface == nil {
1062                 return make([]*PeerConn, 0, cap)
1063         } else {
1064                 return getInterface.([]*PeerConn)[:0]
1065         }
1066 }
1067
1068 // The worst connection is one that hasn't been sent, or sent anything useful for the longest. A bad
1069 // connection is one that usually sends us unwanted pieces, or has been in the worse half of the
1070 // established connections for more than a minute. This is O(n log n). If there was a way to not
1071 // consider the position of a conn relative to the total number, it could be reduced to O(n).
1072 func (t *Torrent) worstBadConn() (ret *PeerConn) {
1073         wcs := worseConnSlice{conns: t.appendUnclosedConns(getPeerConnSlice(len(t.conns)))}
1074         defer peerConnSlices.Put(wcs.conns)
1075         wcs.initKeys()
1076         heap.Init(&wcs)
1077         for wcs.Len() != 0 {
1078                 c := heap.Pop(&wcs).(*PeerConn)
1079                 if c._stats.ChunksReadWasted.Int64() >= 6 && c._stats.ChunksReadWasted.Int64() > c._stats.ChunksReadUseful.Int64() {
1080                         return c
1081                 }
1082                 // If the connection is in the worst half of the established
1083                 // connection quota and is older than a minute.
1084                 if wcs.Len() >= (t.maxEstablishedConns+1)/2 {
1085                         // Give connections 1 minute to prove themselves.
1086                         if time.Since(c.completedHandshake) > time.Minute {
1087                                 return c
1088                         }
1089                 }
1090         }
1091         return nil
1092 }
1093
1094 type PieceStateChange struct {
1095         Index int
1096         PieceState
1097 }
1098
1099 func (t *Torrent) publishPieceChange(piece pieceIndex) {
1100         t.cl._mu.Defer(func() {
1101                 cur := t.pieceState(piece)
1102                 p := &t.pieces[piece]
1103                 if cur != p.publicPieceState {
1104                         p.publicPieceState = cur
1105                         t.pieceStateChanges.Publish(PieceStateChange{
1106                                 int(piece),
1107                                 cur,
1108                         })
1109                 }
1110         })
1111 }
1112
1113 func (t *Torrent) pieceNumPendingChunks(piece pieceIndex) pp.Integer {
1114         if t.pieceComplete(piece) {
1115                 return 0
1116         }
1117         return pp.Integer(t.pieceNumChunks(piece) - t.pieces[piece].numDirtyChunks())
1118 }
1119
1120 func (t *Torrent) pieceAllDirty(piece pieceIndex) bool {
1121         return t.pieces[piece].allChunksDirty()
1122 }
1123
1124 func (t *Torrent) readersChanged() {
1125         t.updateReaderPieces()
1126         t.updateAllPiecePriorities("Torrent.readersChanged")
1127 }
1128
1129 func (t *Torrent) updateReaderPieces() {
1130         t._readerNowPieces, t._readerReadaheadPieces = t.readerPiecePriorities()
1131 }
1132
1133 func (t *Torrent) readerPosChanged(from, to pieceRange) {
1134         if from == to {
1135                 return
1136         }
1137         t.updateReaderPieces()
1138         // Order the ranges, high and low.
1139         l, h := from, to
1140         if l.begin > h.begin {
1141                 l, h = h, l
1142         }
1143         if l.end < h.begin {
1144                 // Two distinct ranges.
1145                 t.updatePiecePriorities(l.begin, l.end, "Torrent.readerPosChanged")
1146                 t.updatePiecePriorities(h.begin, h.end, "Torrent.readerPosChanged")
1147         } else {
1148                 // Ranges overlap.
1149                 end := l.end
1150                 if h.end > end {
1151                         end = h.end
1152                 }
1153                 t.updatePiecePriorities(l.begin, end, "Torrent.readerPosChanged")
1154         }
1155 }
1156
1157 func (t *Torrent) maybeNewConns() {
1158         // Tickle the accept routine.
1159         t.cl.event.Broadcast()
1160         t.openNewConns()
1161 }
1162
1163 func (t *Torrent) piecePriorityChanged(piece pieceIndex, reason string) {
1164         if t._pendingPieces.Contains(uint32(piece)) {
1165                 t.iterPeers(func(c *Peer) {
1166                         // if c.requestState.Interested {
1167                         //      return
1168                         // }
1169                         if !c.isLowOnRequests() {
1170                                 return
1171                         }
1172                         if !c.peerHasPiece(piece) {
1173                                 return
1174                         }
1175                         if c.requestState.Interested && c.peerChoking && !c.peerAllowedFast.Contains(piece) {
1176                                 return
1177                         }
1178                         c.updateRequests(reason)
1179                 })
1180         }
1181         t.maybeNewConns()
1182         t.publishPieceChange(piece)
1183 }
1184
1185 func (t *Torrent) updatePiecePriority(piece pieceIndex, reason string) {
1186         if !t.closed.IsSet() {
1187                 // It would be possible to filter on pure-priority changes here to avoid churning the piece
1188                 // request order.
1189                 t.updatePieceRequestOrder(piece)
1190         }
1191         p := &t.pieces[piece]
1192         newPrio := p.uncachedPriority()
1193         // t.logger.Printf("torrent %p: piece %d: uncached priority: %v", t, piece, newPrio)
1194         if newPrio == PiecePriorityNone {
1195                 if !t._pendingPieces.CheckedRemove(uint32(piece)) {
1196                         return
1197                 }
1198         } else {
1199                 if !t._pendingPieces.CheckedAdd(uint32(piece)) {
1200                         return
1201                 }
1202         }
1203         t.piecePriorityChanged(piece, reason)
1204 }
1205
1206 func (t *Torrent) updateAllPiecePriorities(reason string) {
1207         t.updatePiecePriorities(0, t.numPieces(), reason)
1208 }
1209
1210 // Update all piece priorities in one hit. This function should have the same
1211 // output as updatePiecePriority, but across all pieces.
1212 func (t *Torrent) updatePiecePriorities(begin, end pieceIndex, reason string) {
1213         for i := begin; i < end; i++ {
1214                 t.updatePiecePriority(i, reason)
1215         }
1216 }
1217
1218 // Returns the range of pieces [begin, end) that contains the extent of bytes.
1219 func (t *Torrent) byteRegionPieces(off, size int64) (begin, end pieceIndex) {
1220         if off >= *t.length {
1221                 return
1222         }
1223         if off < 0 {
1224                 size += off
1225                 off = 0
1226         }
1227         if size <= 0 {
1228                 return
1229         }
1230         begin = pieceIndex(off / t.info.PieceLength)
1231         end = pieceIndex((off + size + t.info.PieceLength - 1) / t.info.PieceLength)
1232         if end > pieceIndex(t.info.NumPieces()) {
1233                 end = pieceIndex(t.info.NumPieces())
1234         }
1235         return
1236 }
1237
1238 // Returns true if all iterations complete without breaking. Returns the read regions for all
1239 // readers. The reader regions should not be merged as some callers depend on this method to
1240 // enumerate readers.
1241 func (t *Torrent) forReaderOffsetPieces(f func(begin, end pieceIndex) (more bool)) (all bool) {
1242         for r := range t.readers {
1243                 p := r.pieces
1244                 if p.begin >= p.end {
1245                         continue
1246                 }
1247                 if !f(p.begin, p.end) {
1248                         return false
1249                 }
1250         }
1251         return true
1252 }
1253
1254 func (t *Torrent) piecePriority(piece pieceIndex) piecePriority {
1255         return t.piece(piece).uncachedPriority()
1256 }
1257
1258 func (t *Torrent) pendRequest(req RequestIndex) {
1259         t.piece(t.pieceIndexOfRequestIndex(req)).pendChunkIndex(req % t.chunksPerRegularPiece())
1260 }
1261
1262 func (t *Torrent) pieceCompletionChanged(piece pieceIndex, reason string) {
1263         t.cl.event.Broadcast()
1264         if t.pieceComplete(piece) {
1265                 t.onPieceCompleted(piece)
1266         } else {
1267                 t.onIncompletePiece(piece)
1268         }
1269         t.updatePiecePriority(piece, reason)
1270 }
1271
1272 func (t *Torrent) numReceivedConns() (ret int) {
1273         for c := range t.conns {
1274                 if c.Discovery == PeerSourceIncoming {
1275                         ret++
1276                 }
1277         }
1278         return
1279 }
1280
1281 func (t *Torrent) maxHalfOpen() int {
1282         // Note that if we somehow exceed the maximum established conns, we want
1283         // the negative value to have an effect.
1284         establishedHeadroom := int64(t.maxEstablishedConns - len(t.conns))
1285         extraIncoming := int64(t.numReceivedConns() - t.maxEstablishedConns/2)
1286         // We want to allow some experimentation with new peers, and to try to
1287         // upset an oversupply of received connections.
1288         return int(min(max(5, extraIncoming)+establishedHeadroom, int64(t.cl.config.HalfOpenConnsPerTorrent)))
1289 }
1290
1291 func (t *Torrent) openNewConns() (initiated int) {
1292         defer t.updateWantPeersEvent()
1293         for t.peers.Len() != 0 {
1294                 if !t.wantConns() {
1295                         return
1296                 }
1297                 if len(t.halfOpen) >= t.maxHalfOpen() {
1298                         return
1299                 }
1300                 if len(t.cl.dialers) == 0 {
1301                         return
1302                 }
1303                 if t.cl.numHalfOpen >= t.cl.config.TotalHalfOpenConns {
1304                         return
1305                 }
1306                 p := t.peers.PopMax()
1307                 t.initiateConn(p)
1308                 initiated++
1309         }
1310         return
1311 }
1312
1313 func (t *Torrent) updatePieceCompletion(piece pieceIndex) bool {
1314         p := t.piece(piece)
1315         uncached := t.pieceCompleteUncached(piece)
1316         cached := p.completion()
1317         changed := cached != uncached
1318         complete := uncached.Complete
1319         p.storageCompletionOk = uncached.Ok
1320         x := uint32(piece)
1321         if complete {
1322                 t._completedPieces.Add(x)
1323                 t.openNewConns()
1324         } else {
1325                 t._completedPieces.Remove(x)
1326         }
1327         p.t.updatePieceRequestOrder(piece)
1328         t.updateComplete()
1329         if complete && len(p.dirtiers) != 0 {
1330                 t.logger.Printf("marked piece %v complete but still has dirtiers", piece)
1331         }
1332         if changed {
1333                 log.Fstr("piece %d completion changed: %+v -> %+v", piece, cached, uncached).LogLevel(log.Debug, t.logger)
1334                 t.pieceCompletionChanged(piece, "Torrent.updatePieceCompletion")
1335         }
1336         return changed
1337 }
1338
1339 // Non-blocking read. Client lock is not required.
1340 func (t *Torrent) readAt(b []byte, off int64) (n int, err error) {
1341         for len(b) != 0 {
1342                 p := &t.pieces[off/t.info.PieceLength]
1343                 p.waitNoPendingWrites()
1344                 var n1 int
1345                 n1, err = p.Storage().ReadAt(b, off-p.Info().Offset())
1346                 if n1 == 0 {
1347                         break
1348                 }
1349                 off += int64(n1)
1350                 n += n1
1351                 b = b[n1:]
1352         }
1353         return
1354 }
1355
1356 // Returns an error if the metadata was completed, but couldn't be set for some reason. Blame it on
1357 // the last peer to contribute. TODO: Actually we shouldn't blame peers for failure to open storage
1358 // etc. Also we should probably cached metadata pieces per-Peer, to isolate failure appropriately.
1359 func (t *Torrent) maybeCompleteMetadata() error {
1360         if t.haveInfo() {
1361                 // Nothing to do.
1362                 return nil
1363         }
1364         if !t.haveAllMetadataPieces() {
1365                 // Don't have enough metadata pieces.
1366                 return nil
1367         }
1368         err := t.setInfoBytesLocked(t.metadataBytes)
1369         if err != nil {
1370                 t.invalidateMetadata()
1371                 return fmt.Errorf("error setting info bytes: %s", err)
1372         }
1373         if t.cl.config.Debug {
1374                 t.logger.Printf("%s: got metadata from peers", t)
1375         }
1376         return nil
1377 }
1378
1379 func (t *Torrent) readerPiecePriorities() (now, readahead bitmap.Bitmap) {
1380         t.forReaderOffsetPieces(func(begin, end pieceIndex) bool {
1381                 if end > begin {
1382                         now.Add(bitmap.BitIndex(begin))
1383                         readahead.AddRange(bitmap.BitRange(begin)+1, bitmap.BitRange(end))
1384                 }
1385                 return true
1386         })
1387         return
1388 }
1389
1390 func (t *Torrent) needData() bool {
1391         if t.closed.IsSet() {
1392                 return false
1393         }
1394         if !t.haveInfo() {
1395                 return true
1396         }
1397         return !t._pendingPieces.IsEmpty()
1398 }
1399
1400 func appendMissingStrings(old, new []string) (ret []string) {
1401         ret = old
1402 new:
1403         for _, n := range new {
1404                 for _, o := range old {
1405                         if o == n {
1406                                 continue new
1407                         }
1408                 }
1409                 ret = append(ret, n)
1410         }
1411         return
1412 }
1413
1414 func appendMissingTrackerTiers(existing [][]string, minNumTiers int) (ret [][]string) {
1415         ret = existing
1416         for minNumTiers > len(ret) {
1417                 ret = append(ret, nil)
1418         }
1419         return
1420 }
1421
1422 func (t *Torrent) addTrackers(announceList [][]string) {
1423         fullAnnounceList := &t.metainfo.AnnounceList
1424         t.metainfo.AnnounceList = appendMissingTrackerTiers(*fullAnnounceList, len(announceList))
1425         for tierIndex, trackerURLs := range announceList {
1426                 (*fullAnnounceList)[tierIndex] = appendMissingStrings((*fullAnnounceList)[tierIndex], trackerURLs)
1427         }
1428         t.startMissingTrackerScrapers()
1429         t.updateWantPeersEvent()
1430 }
1431
1432 // Don't call this before the info is available.
1433 func (t *Torrent) bytesCompleted() int64 {
1434         if !t.haveInfo() {
1435                 return 0
1436         }
1437         return *t.length - t.bytesLeft()
1438 }
1439
1440 func (t *Torrent) SetInfoBytes(b []byte) (err error) {
1441         t.cl.lock()
1442         defer t.cl.unlock()
1443         return t.setInfoBytesLocked(b)
1444 }
1445
1446 // Returns true if connection is removed from torrent.Conns.
1447 func (t *Torrent) deletePeerConn(c *PeerConn) (ret bool) {
1448         if !c.closed.IsSet() {
1449                 panic("connection is not closed")
1450                 // There are behaviours prevented by the closed state that will fail
1451                 // if the connection has been deleted.
1452         }
1453         _, ret = t.conns[c]
1454         delete(t.conns, c)
1455         // Avoid adding a drop event more than once. Probably we should track whether we've generated
1456         // the drop event against the PexConnState instead.
1457         if ret {
1458                 if !t.cl.config.DisablePEX {
1459                         t.pex.Drop(c)
1460                 }
1461         }
1462         torrent.Add("deleted connections", 1)
1463         c.deleteAllRequests("Torrent.deletePeerConn")
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, piece)
2053                                         c.ban()
2054                                 }
2055                         }
2056                 }
2057                 t.onIncompletePiece(piece)
2058                 p.Storage().MarkNotComplete()
2059         }
2060         t.updatePieceCompletion(piece)
2061 }
2062
2063 func (t *Torrent) cancelRequestsForPiece(piece pieceIndex) {
2064         for ri := t.pieceRequestIndexOffset(piece); ri < t.pieceRequestIndexOffset(piece+1); ri++ {
2065                 t.cancelRequest(ri)
2066         }
2067 }
2068
2069 func (t *Torrent) onPieceCompleted(piece pieceIndex) {
2070         t.pendAllChunkSpecs(piece)
2071         t.cancelRequestsForPiece(piece)
2072         t.piece(piece).readerCond.Broadcast()
2073         for conn := range t.conns {
2074                 conn.have(piece)
2075                 t.maybeDropMutuallyCompletePeer(&conn.Peer)
2076         }
2077 }
2078
2079 // Called when a piece is found to be not complete.
2080 func (t *Torrent) onIncompletePiece(piece pieceIndex) {
2081         if t.pieceAllDirty(piece) {
2082                 t.pendAllChunkSpecs(piece)
2083         }
2084         if !t.wantPieceIndex(piece) {
2085                 // t.logger.Printf("piece %d incomplete and unwanted", piece)
2086                 return
2087         }
2088         // We could drop any connections that we told we have a piece that we
2089         // don't here. But there's a test failure, and it seems clients don't care
2090         // if you request pieces that you already claim to have. Pruning bad
2091         // connections might just remove any connections that aren't treating us
2092         // favourably anyway.
2093
2094         // for c := range t.conns {
2095         //      if c.sentHave(piece) {
2096         //              c.drop()
2097         //      }
2098         // }
2099         t.iterPeers(func(conn *Peer) {
2100                 if conn.peerHasPiece(piece) {
2101                         conn.updateRequests("piece incomplete")
2102                 }
2103         })
2104 }
2105
2106 func (t *Torrent) tryCreateMorePieceHashers() {
2107         for !t.closed.IsSet() && t.activePieceHashes < 2 && t.tryCreatePieceHasher() {
2108         }
2109 }
2110
2111 func (t *Torrent) tryCreatePieceHasher() bool {
2112         if t.storage == nil {
2113                 return false
2114         }
2115         pi, ok := t.getPieceToHash()
2116         if !ok {
2117                 return false
2118         }
2119         p := t.piece(pi)
2120         t.piecesQueuedForHash.Remove(bitmap.BitIndex(pi))
2121         p.hashing = true
2122         t.publishPieceChange(pi)
2123         t.updatePiecePriority(pi, "Torrent.tryCreatePieceHasher")
2124         t.storageLock.RLock()
2125         t.activePieceHashes++
2126         go t.pieceHasher(pi)
2127         return true
2128 }
2129
2130 func (t *Torrent) getPieceToHash() (ret pieceIndex, ok bool) {
2131         t.piecesQueuedForHash.IterTyped(func(i pieceIndex) bool {
2132                 if t.piece(i).hashing {
2133                         return true
2134                 }
2135                 ret = i
2136                 ok = true
2137                 return false
2138         })
2139         return
2140 }
2141
2142 func (t *Torrent) dropBannedPeers() {
2143         t.iterPeers(func(p *Peer) {
2144                 remoteIp := p.remoteIp()
2145                 if remoteIp == nil {
2146                         if p.bannableAddr.Ok() {
2147                                 t.logger.WithDefaultLevel(log.Debug).Printf("can't get remote ip for peer %v", p)
2148                         }
2149                         return
2150                 }
2151                 netipAddr := netip.MustParseAddr(remoteIp.String())
2152                 if Some(netipAddr) != p.bannableAddr {
2153                         t.logger.WithDefaultLevel(log.Debug).Printf(
2154                                 "peer remote ip does not match its bannable addr [peer=%v, remote ip=%v, bannable addr=%v]",
2155                                 p, remoteIp, p.bannableAddr)
2156                 }
2157                 if _, ok := t.cl.badPeerIPs[netipAddr]; ok {
2158                         // Should this be a close?
2159                         p.drop()
2160                         t.logger.WithDefaultLevel(log.Debug).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                         t.logger.WithDefaultLevel(log.Debug).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 type AddWebSeedsOpt func(*webseed.Client)
2347
2348 // Sets the WebSeed trailing path escaper for a webseed.Client.
2349 func WebSeedPathEscaper(custom webseed.PathEscaper) AddWebSeedsOpt {
2350         return func(c *webseed.Client) {
2351                 c.PathEscaper = custom
2352         }
2353 }
2354
2355 func (t *Torrent) AddWebSeeds(urls []string, opts ...AddWebSeedsOpt) {
2356         t.cl.lock()
2357         defer t.cl.unlock()
2358         for _, u := range urls {
2359                 t.addWebSeed(u, opts...)
2360         }
2361 }
2362
2363 func (t *Torrent) addWebSeed(url string, opts ...AddWebSeedsOpt) {
2364         if t.cl.config.DisableWebseeds {
2365                 return
2366         }
2367         if _, ok := t.webSeeds[url]; ok {
2368                 return
2369         }
2370         // I don't think Go http supports pipelining requests. However, we can have more ready to go
2371         // right away. This value should be some multiple of the number of connections to a host. I
2372         // would expect that double maxRequests plus a bit would be appropriate. This value is based on
2373         // downloading Sintel (08ada5a7a6183aae1e09d831df6748d566095a10) from
2374         // "https://webtorrent.io/torrents/".
2375         const maxRequests = 16
2376         ws := webseedPeer{
2377                 peer: Peer{
2378                         t:                        t,
2379                         outgoing:                 true,
2380                         Network:                  "http",
2381                         reconciledHandshakeStats: true,
2382                         // This should affect how often we have to recompute requests for this peer. Note that
2383                         // because we can request more than 1 thing at a time over HTTP, we will hit the low
2384                         // requests mark more often, so recomputation is probably sooner than with regular peer
2385                         // conns. ~4x maxRequests would be about right.
2386                         PeerMaxRequests: 128,
2387                         // TODO: Set ban prefix?
2388                         RemoteAddr: remoteAddrFromUrl(url),
2389                         callbacks:  t.callbacks(),
2390                 },
2391                 client: webseed.Client{
2392                         HttpClient: t.cl.httpClient,
2393                         Url:        url,
2394                         ResponseBodyWrapper: func(r io.Reader) io.Reader {
2395                                 return &rateLimitedReader{
2396                                         l: t.cl.config.DownloadRateLimiter,
2397                                         r: r,
2398                                 }
2399                         },
2400                 },
2401                 activeRequests: make(map[Request]webseed.Request, maxRequests),
2402                 maxRequests:    maxRequests,
2403         }
2404         ws.peer.initRequestState()
2405         for _, opt := range opts {
2406                 opt(&ws.client)
2407         }
2408         ws.peer.initUpdateRequestsTimer()
2409         ws.requesterCond.L = t.cl.locker()
2410         for i := 0; i < maxRequests; i += 1 {
2411                 go ws.requester(i)
2412         }
2413         for _, f := range t.callbacks().NewPeer {
2414                 f(&ws.peer)
2415         }
2416         ws.peer.logger = t.logger.WithContextValue(&ws)
2417         ws.peer.peerImpl = &ws
2418         if t.haveInfo() {
2419                 ws.onGotInfo(t.info)
2420         }
2421         t.webSeeds[url] = &ws.peer
2422 }
2423
2424 func (t *Torrent) peerIsActive(p *Peer) (active bool) {
2425         t.iterPeers(func(p1 *Peer) {
2426                 if p1 == p {
2427                         active = true
2428                 }
2429         })
2430         return
2431 }
2432
2433 func (t *Torrent) requestIndexToRequest(ri RequestIndex) Request {
2434         index := t.pieceIndexOfRequestIndex(ri)
2435         return Request{
2436                 pp.Integer(index),
2437                 t.piece(index).chunkIndexSpec(ri % t.chunksPerRegularPiece()),
2438         }
2439 }
2440
2441 func (t *Torrent) requestIndexFromRequest(r Request) RequestIndex {
2442         return t.pieceRequestIndexOffset(pieceIndex(r.Index)) + RequestIndex(r.Begin/t.chunkSize)
2443 }
2444
2445 func (t *Torrent) pieceRequestIndexOffset(piece pieceIndex) RequestIndex {
2446         return RequestIndex(piece) * t.chunksPerRegularPiece()
2447 }
2448
2449 func (t *Torrent) updateComplete() {
2450         t.Complete.SetBool(t.haveAllPieces())
2451 }
2452
2453 func (t *Torrent) cancelRequest(r RequestIndex) *Peer {
2454         p := t.requestingPeer(r)
2455         if p != nil {
2456                 p.cancel(r)
2457         }
2458         // TODO: This is a check that an old invariant holds. It can be removed after some testing.
2459         //delete(t.pendingRequests, r)
2460         if _, ok := t.requestState[r]; ok {
2461                 panic("expected request state to be gone")
2462         }
2463         return p
2464 }
2465
2466 func (t *Torrent) requestingPeer(r RequestIndex) *Peer {
2467         return t.requestState[r].peer
2468 }
2469
2470 func (t *Torrent) addConnWithAllPieces(p *Peer) {
2471         if t.connsWithAllPieces == nil {
2472                 t.connsWithAllPieces = make(map[*Peer]struct{}, t.maxEstablishedConns)
2473         }
2474         t.connsWithAllPieces[p] = struct{}{}
2475 }
2476
2477 func (t *Torrent) deleteConnWithAllPieces(p *Peer) bool {
2478         _, ok := t.connsWithAllPieces[p]
2479         delete(t.connsWithAllPieces, p)
2480         return ok
2481 }
2482
2483 func (t *Torrent) numActivePeers() int {
2484         return len(t.conns) + len(t.webSeeds)
2485 }
2486
2487 func (t *Torrent) hasStorageCap() bool {
2488         f := t.storage.Capacity
2489         if f == nil {
2490                 return false
2491         }
2492         _, ok := (*f)()
2493         return ok
2494 }
2495
2496 func (t *Torrent) pieceIndexOfRequestIndex(ri RequestIndex) pieceIndex {
2497         return pieceIndex(ri / t.chunksPerRegularPiece())
2498 }
2499
2500 type requestState struct {
2501         peer *Peer
2502         when time.Time
2503 }