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