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