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