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