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