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