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