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