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