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