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