]> Sergey Matveev's repositories - btrtrc.git/blob - torrent.go
32b7e5fda1a74e67b0fa24c8f304d6e9541e7aad
[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         if t.displayName != "" {
498                 return t.displayName
499         }
500         return "infohash:" + t.infoHash.HexString()
501 }
502
503 func (t *Torrent) pieceState(index pieceIndex) (ret PieceState) {
504         p := &t.pieces[index]
505         ret.Priority = t.piecePriority(index)
506         ret.Completion = p.completion()
507         ret.QueuedForHash = p.queuedForHash()
508         ret.Hashing = p.hashing
509         ret.Checking = ret.QueuedForHash || ret.Hashing
510         ret.Marking = p.marking
511         if !ret.Complete && t.piecePartiallyDownloaded(index) {
512                 ret.Partial = true
513         }
514         return
515 }
516
517 func (t *Torrent) metadataPieceSize(piece int) int {
518         return metadataPieceSize(len(t.metadataBytes), piece)
519 }
520
521 func (t *Torrent) newMetadataExtensionMessage(c *PeerConn, msgType int, piece int, data []byte) pp.Message {
522         d := map[string]int{
523                 "msg_type": msgType,
524                 "piece":    piece,
525         }
526         if data != nil {
527                 d["total_size"] = len(t.metadataBytes)
528         }
529         p := bencode.MustMarshal(d)
530         return pp.Message{
531                 Type:            pp.Extended,
532                 ExtendedID:      c.PeerExtensionIDs[pp.ExtensionNameMetadata],
533                 ExtendedPayload: append(p, data...),
534         }
535 }
536
537 func (t *Torrent) pieceStateRuns() (ret PieceStateRuns) {
538         rle := missinggo.NewRunLengthEncoder(func(el interface{}, count uint64) {
539                 ret = append(ret, PieceStateRun{
540                         PieceState: el.(PieceState),
541                         Length:     int(count),
542                 })
543         })
544         for index := range t.pieces {
545                 rle.Append(t.pieceState(pieceIndex(index)), 1)
546         }
547         rle.Flush()
548         return
549 }
550
551 // Produces a small string representing a PieceStateRun.
552 func (psr PieceStateRun) String() (ret string) {
553         ret = fmt.Sprintf("%d", psr.Length)
554         ret += func() string {
555                 switch psr.Priority {
556                 case PiecePriorityNext:
557                         return "N"
558                 case PiecePriorityNormal:
559                         return "."
560                 case PiecePriorityReadahead:
561                         return "R"
562                 case PiecePriorityNow:
563                         return "!"
564                 case PiecePriorityHigh:
565                         return "H"
566                 default:
567                         return ""
568                 }
569         }()
570         if psr.Hashing {
571                 ret += "H"
572         }
573         if psr.QueuedForHash {
574                 ret += "Q"
575         }
576         if psr.Marking {
577                 ret += "M"
578         }
579         if psr.Partial {
580                 ret += "P"
581         }
582         if psr.Complete {
583                 ret += "C"
584         }
585         if !psr.Ok {
586                 ret += "?"
587         }
588         return
589 }
590
591 func (t *Torrent) writeStatus(w io.Writer) {
592         fmt.Fprintf(w, "Infohash: %s\n", t.infoHash.HexString())
593         fmt.Fprintf(w, "Metadata length: %d\n", t.metadataSize())
594         if !t.haveInfo() {
595                 fmt.Fprintf(w, "Metadata have: ")
596                 for _, h := range t.metadataCompletedChunks {
597                         fmt.Fprintf(w, "%c", func() rune {
598                                 if h {
599                                         return 'H'
600                                 } else {
601                                         return '.'
602                                 }
603                         }())
604                 }
605                 fmt.Fprintln(w)
606         }
607         fmt.Fprintf(w, "Piece length: %s\n", func() string {
608                 if t.haveInfo() {
609                         return fmt.Sprint(t.usualPieceSize())
610                 } else {
611                         return "?"
612                 }
613         }())
614         if t.info != nil {
615                 fmt.Fprintf(w, "Num Pieces: %d (%d completed)\n", t.numPieces(), t.numPiecesCompleted())
616                 fmt.Fprintf(w, "Piece States: %s", t.pieceStateRuns())
617                 fmt.Fprintln(w)
618         }
619         fmt.Fprintf(w, "Reader Pieces:")
620         t.forReaderOffsetPieces(func(begin, end pieceIndex) (again bool) {
621                 fmt.Fprintf(w, " %d:%d", begin, end)
622                 return true
623         })
624         fmt.Fprintln(w)
625
626         fmt.Fprintf(w, "Enabled trackers:\n")
627         func() {
628                 tw := tabwriter.NewWriter(w, 0, 0, 2, ' ', 0)
629                 fmt.Fprintf(tw, "    URL\tExtra\n")
630                 for _, ta := range slices.Sort(slices.FromMapElems(t.trackerAnnouncers), func(l, r torrentTrackerAnnouncer) bool {
631                         lu := l.URL()
632                         ru := r.URL()
633                         var luns, runs url.URL = *lu, *ru
634                         luns.Scheme = ""
635                         runs.Scheme = ""
636                         var ml missinggo.MultiLess
637                         ml.StrictNext(luns.String() == runs.String(), luns.String() < runs.String())
638                         ml.StrictNext(lu.String() == ru.String(), lu.String() < ru.String())
639                         return ml.Less()
640                 }).([]torrentTrackerAnnouncer) {
641                         fmt.Fprintf(tw, "    %q\t%v\n", ta.URL(), ta.statusLine())
642                 }
643                 tw.Flush()
644         }()
645
646         fmt.Fprintf(w, "DHT Announces: %d\n", t.numDHTAnnounces)
647
648         spew.NewDefaultConfig()
649         spew.Fdump(w, t.statsLocked())
650
651         peers := t.peersAsSlice()
652         sort.Slice(peers, func(i, j int) bool {
653                 return worseConn(peers[i], peers[j])
654         })
655         for i, c := range peers {
656                 fmt.Fprintf(w, "%2d. ", i+1)
657                 c.writeStatus(w, t)
658         }
659 }
660
661 func (t *Torrent) haveInfo() bool {
662         return t.info != nil
663 }
664
665 // Returns a run-time generated MetaInfo that includes the info bytes and
666 // announce-list as currently known to the client.
667 func (t *Torrent) newMetaInfo() metainfo.MetaInfo {
668         return metainfo.MetaInfo{
669                 CreationDate: time.Now().Unix(),
670                 Comment:      "dynamic metainfo from client",
671                 CreatedBy:    "go.torrent",
672                 AnnounceList: t.metainfo.UpvertedAnnounceList().Clone(),
673                 InfoBytes: func() []byte {
674                         if t.haveInfo() {
675                                 return t.metadataBytes
676                         } else {
677                                 return nil
678                         }
679                 }(),
680                 UrlList: func() []string {
681                         ret := make([]string, 0, len(t.webSeeds))
682                         for url := range t.webSeeds {
683                                 ret = append(ret, url)
684                         }
685                         return ret
686                 }(),
687         }
688 }
689
690 func (t *Torrent) BytesMissing() int64 {
691         t.cl.rLock()
692         defer t.cl.rUnlock()
693         return t.bytesMissingLocked()
694 }
695
696 func (t *Torrent) bytesMissingLocked() int64 {
697         return t.bytesLeft()
698 }
699
700 func (t *Torrent) bytesLeft() (left int64) {
701         bitmap.Flip(t._completedPieces, 0, bitmap.BitIndex(t.numPieces())).IterTyped(func(piece int) bool {
702                 p := &t.pieces[piece]
703                 left += int64(p.length() - p.numDirtyBytes())
704                 return true
705         })
706         return
707 }
708
709 // Bytes left to give in tracker announces.
710 func (t *Torrent) bytesLeftAnnounce() int64 {
711         if t.haveInfo() {
712                 return t.bytesLeft()
713         } else {
714                 return -1
715         }
716 }
717
718 func (t *Torrent) piecePartiallyDownloaded(piece pieceIndex) bool {
719         if t.pieceComplete(piece) {
720                 return false
721         }
722         if t.pieceAllDirty(piece) {
723                 return false
724         }
725         return t.pieces[piece].hasDirtyChunks()
726 }
727
728 func (t *Torrent) usualPieceSize() int {
729         return int(t.info.PieceLength)
730 }
731
732 func (t *Torrent) numPieces() pieceIndex {
733         return pieceIndex(t.info.NumPieces())
734 }
735
736 func (t *Torrent) numPiecesCompleted() (num int) {
737         return t._completedPieces.Len()
738 }
739
740 func (t *Torrent) close() (err error) {
741         t.closed.Set()
742         t.tickleReaders()
743         if t.storage != nil {
744                 func() {
745                         t.storageLock.Lock()
746                         defer t.storageLock.Unlock()
747                         t.storage.Close()
748                 }()
749         }
750         t.iterPeers(func(p *Peer) {
751                 p.close()
752         })
753         t.pex.Reset()
754         t.cl.event.Broadcast()
755         t.pieceStateChanges.Close()
756         t.updateWantPeersEvent()
757         return
758 }
759
760 func (t *Torrent) requestOffset(r Request) int64 {
761         return torrentRequestOffset(*t.length, int64(t.usualPieceSize()), r)
762 }
763
764 // Return the request that would include the given offset into the torrent data. Returns !ok if
765 // there is no such request.
766 func (t *Torrent) offsetRequest(off int64) (req Request, ok bool) {
767         return torrentOffsetRequest(*t.length, t.info.PieceLength, int64(t.chunkSize), off)
768 }
769
770 func (t *Torrent) writeChunk(piece int, begin int64, data []byte) (err error) {
771         defer perf.ScopeTimerErr(&err)()
772         n, err := t.pieces[piece].Storage().WriteAt(data, begin)
773         if err == nil && n != len(data) {
774                 err = io.ErrShortWrite
775         }
776         return err
777 }
778
779 func (t *Torrent) bitfield() (bf []bool) {
780         bf = make([]bool, t.numPieces())
781         t._completedPieces.IterTyped(func(piece int) (again bool) {
782                 bf[piece] = true
783                 return true
784         })
785         return
786 }
787
788 func (t *Torrent) pieceNumChunks(piece pieceIndex) pp.Integer {
789         return (t.pieceLength(piece) + t.chunkSize - 1) / t.chunkSize
790 }
791
792 func (t *Torrent) pendAllChunkSpecs(pieceIndex pieceIndex) {
793         t.pieces[pieceIndex]._dirtyChunks.Clear()
794 }
795
796 func (t *Torrent) pieceLength(piece pieceIndex) pp.Integer {
797         if t.info.PieceLength == 0 {
798                 // There will be no variance amongst pieces. Only pain.
799                 return 0
800         }
801         if piece == t.numPieces()-1 {
802                 ret := pp.Integer(*t.length % t.info.PieceLength)
803                 if ret != 0 {
804                         return ret
805                 }
806         }
807         return pp.Integer(t.info.PieceLength)
808 }
809
810 func (t *Torrent) hashPiece(piece pieceIndex) (ret metainfo.Hash, err error) {
811         hash := pieceHash.New()
812         p := t.piece(piece)
813         p.waitNoPendingWrites()
814         storagePiece := t.pieces[piece].Storage()
815         const logPieceContents = false
816         if logPieceContents {
817                 var examineBuf bytes.Buffer
818                 _, err = storagePiece.WriteTo(io.MultiWriter(hash, &examineBuf))
819                 log.Printf("hashed %q with copy err %v", examineBuf.Bytes(), err)
820         } else {
821                 _, err = storagePiece.WriteTo(hash)
822         }
823         missinggo.CopyExact(&ret, hash.Sum(nil))
824         return
825 }
826
827 func (t *Torrent) haveAnyPieces() bool {
828         return t._completedPieces.Len() != 0
829 }
830
831 func (t *Torrent) haveAllPieces() bool {
832         if !t.haveInfo() {
833                 return false
834         }
835         return t._completedPieces.Len() == bitmap.BitIndex(t.numPieces())
836 }
837
838 func (t *Torrent) havePiece(index pieceIndex) bool {
839         return t.haveInfo() && t.pieceComplete(index)
840 }
841
842 func (t *Torrent) maybeDropMutuallyCompletePeer(
843         // I'm not sure about taking peer here, not all peer implementations actually drop. Maybe that's okay?
844         p *Peer,
845 ) {
846         if !t.cl.config.DropMutuallyCompletePeers {
847                 return
848         }
849         if !t.haveAllPieces() {
850                 return
851         }
852         if all, known := p.peerHasAllPieces(); !(known && all) {
853                 return
854         }
855         if p.useful() {
856                 return
857         }
858         t.logger.WithDefaultLevel(log.Debug).Printf("dropping %v, which is mutually complete", p)
859         p.drop()
860 }
861
862 func (t *Torrent) haveChunk(r Request) (ret bool) {
863         // defer func() {
864         //      log.Println("have chunk", r, ret)
865         // }()
866         if !t.haveInfo() {
867                 return false
868         }
869         if t.pieceComplete(pieceIndex(r.Index)) {
870                 return true
871         }
872         p := &t.pieces[r.Index]
873         return !p.pendingChunk(r.ChunkSpec, t.chunkSize)
874 }
875
876 func chunkIndex(cs ChunkSpec, chunkSize pp.Integer) int {
877         return int(cs.Begin / chunkSize)
878 }
879
880 func (t *Torrent) wantPieceIndex(index pieceIndex) bool {
881         if !t.haveInfo() {
882                 return false
883         }
884         if index < 0 || index >= t.numPieces() {
885                 return false
886         }
887         p := &t.pieces[index]
888         if p.queuedForHash() {
889                 return false
890         }
891         if p.hashing {
892                 return false
893         }
894         if t.pieceComplete(index) {
895                 return false
896         }
897         if t._pendingPieces.Contains(bitmap.BitIndex(index)) {
898                 return true
899         }
900         // t.logger.Printf("piece %d not pending", index)
901         return !t.forReaderOffsetPieces(func(begin, end pieceIndex) bool {
902                 return index < begin || index >= end
903         })
904 }
905
906 // The worst connection is one that hasn't been sent, or sent anything useful for the longest. A bad
907 // connection is one that usually sends us unwanted pieces, or has been in worser half of the
908 // established connections for more than a minute.
909 func (t *Torrent) worstBadConn() *PeerConn {
910         wcs := worseConnSlice{t.unclosedConnsAsSlice()}
911         heap.Init(&wcs)
912         for wcs.Len() != 0 {
913                 c := heap.Pop(&wcs).(*PeerConn)
914                 if c._stats.ChunksReadWasted.Int64() >= 6 && c._stats.ChunksReadWasted.Int64() > c._stats.ChunksReadUseful.Int64() {
915                         return c
916                 }
917                 // If the connection is in the worst half of the established
918                 // connection quota and is older than a minute.
919                 if wcs.Len() >= (t.maxEstablishedConns+1)/2 {
920                         // Give connections 1 minute to prove themselves.
921                         if time.Since(c.completedHandshake) > time.Minute {
922                                 return c
923                         }
924                 }
925         }
926         return nil
927 }
928
929 type PieceStateChange struct {
930         Index int
931         PieceState
932 }
933
934 func (t *Torrent) publishPieceChange(piece pieceIndex) {
935         t.cl._mu.Defer(func() {
936                 cur := t.pieceState(piece)
937                 p := &t.pieces[piece]
938                 if cur != p.publicPieceState {
939                         p.publicPieceState = cur
940                         t.pieceStateChanges.Publish(PieceStateChange{
941                                 int(piece),
942                                 cur,
943                         })
944                 }
945         })
946 }
947
948 func (t *Torrent) pieceNumPendingChunks(piece pieceIndex) pp.Integer {
949         if t.pieceComplete(piece) {
950                 return 0
951         }
952         return t.pieceNumChunks(piece) - t.pieces[piece].numDirtyChunks()
953 }
954
955 func (t *Torrent) pieceAllDirty(piece pieceIndex) bool {
956         return t.pieces[piece]._dirtyChunks.Len() == int(t.pieceNumChunks(piece))
957 }
958
959 func (t *Torrent) readersChanged() {
960         t.updateReaderPieces()
961         t.updateAllPiecePriorities()
962 }
963
964 func (t *Torrent) updateReaderPieces() {
965         t._readerNowPieces, t._readerReadaheadPieces = t.readerPiecePriorities()
966 }
967
968 func (t *Torrent) readerPosChanged(from, to pieceRange) {
969         if from == to {
970                 return
971         }
972         t.updateReaderPieces()
973         // Order the ranges, high and low.
974         l, h := from, to
975         if l.begin > h.begin {
976                 l, h = h, l
977         }
978         if l.end < h.begin {
979                 // Two distinct ranges.
980                 t.updatePiecePriorities(l.begin, l.end)
981                 t.updatePiecePriorities(h.begin, h.end)
982         } else {
983                 // Ranges overlap.
984                 end := l.end
985                 if h.end > end {
986                         end = h.end
987                 }
988                 t.updatePiecePriorities(l.begin, end)
989         }
990 }
991
992 func (t *Torrent) maybeNewConns() {
993         // Tickle the accept routine.
994         t.cl.event.Broadcast()
995         t.openNewConns()
996 }
997
998 func (t *Torrent) piecePriorityChanged(piece pieceIndex) {
999         // t.logger.Printf("piece %d priority changed", piece)
1000         t.iterPeers(func(c *Peer) {
1001                 if c.updatePiecePriority(piece) {
1002                         // log.Print("conn piece priority changed")
1003                         c.updateRequests()
1004                 }
1005         })
1006         t.maybeNewConns()
1007         t.publishPieceChange(piece)
1008 }
1009
1010 func (t *Torrent) updatePiecePriority(piece pieceIndex) {
1011         p := &t.pieces[piece]
1012         newPrio := p.uncachedPriority()
1013         // t.logger.Printf("torrent %p: piece %d: uncached priority: %v", t, piece, newPrio)
1014         if newPrio == PiecePriorityNone {
1015                 if !t._pendingPieces.Remove(bitmap.BitIndex(piece)) {
1016                         return
1017                 }
1018         } else {
1019                 if !t._pendingPieces.Set(bitmap.BitIndex(piece), newPrio.BitmapPriority()) {
1020                         return
1021                 }
1022         }
1023         t.piecePriorityChanged(piece)
1024 }
1025
1026 func (t *Torrent) updateAllPiecePriorities() {
1027         t.updatePiecePriorities(0, t.numPieces())
1028 }
1029
1030 // Update all piece priorities in one hit. This function should have the same
1031 // output as updatePiecePriority, but across all pieces.
1032 func (t *Torrent) updatePiecePriorities(begin, end pieceIndex) {
1033         for i := begin; i < end; i++ {
1034                 t.updatePiecePriority(i)
1035         }
1036 }
1037
1038 // Returns the range of pieces [begin, end) that contains the extent of bytes.
1039 func (t *Torrent) byteRegionPieces(off, size int64) (begin, end pieceIndex) {
1040         if off >= *t.length {
1041                 return
1042         }
1043         if off < 0 {
1044                 size += off
1045                 off = 0
1046         }
1047         if size <= 0 {
1048                 return
1049         }
1050         begin = pieceIndex(off / t.info.PieceLength)
1051         end = pieceIndex((off + size + t.info.PieceLength - 1) / t.info.PieceLength)
1052         if end > pieceIndex(t.info.NumPieces()) {
1053                 end = pieceIndex(t.info.NumPieces())
1054         }
1055         return
1056 }
1057
1058 // Returns true if all iterations complete without breaking. Returns the read
1059 // regions for all readers. The reader regions should not be merged as some
1060 // callers depend on this method to enumerate readers.
1061 func (t *Torrent) forReaderOffsetPieces(f func(begin, end pieceIndex) (more bool)) (all bool) {
1062         for r := range t.readers {
1063                 p := r.pieces
1064                 if p.begin >= p.end {
1065                         continue
1066                 }
1067                 if !f(p.begin, p.end) {
1068                         return false
1069                 }
1070         }
1071         return true
1072 }
1073
1074 func (t *Torrent) piecePriority(piece pieceIndex) piecePriority {
1075         prio, ok := t._pendingPieces.GetPriority(bitmap.BitIndex(piece))
1076         if !ok {
1077                 return PiecePriorityNone
1078         }
1079         if prio > 0 {
1080                 panic(prio)
1081         }
1082         ret := piecePriority(-prio)
1083         if ret == PiecePriorityNone {
1084                 panic(piece)
1085         }
1086         return ret
1087 }
1088
1089 func (t *Torrent) pendRequest(req Request) {
1090         ci := chunkIndex(req.ChunkSpec, t.chunkSize)
1091         t.pieces[req.Index].pendChunkIndex(ci)
1092 }
1093
1094 func (t *Torrent) pieceCompletionChanged(piece pieceIndex) {
1095         t.tickleReaders()
1096         t.cl.event.Broadcast()
1097         if t.pieceComplete(piece) {
1098                 t.onPieceCompleted(piece)
1099         } else {
1100                 t.onIncompletePiece(piece)
1101         }
1102         t.updatePiecePriority(piece)
1103 }
1104
1105 func (t *Torrent) numReceivedConns() (ret int) {
1106         for c := range t.conns {
1107                 if c.Discovery == PeerSourceIncoming {
1108                         ret++
1109                 }
1110         }
1111         return
1112 }
1113
1114 func (t *Torrent) maxHalfOpen() int {
1115         // Note that if we somehow exceed the maximum established conns, we want
1116         // the negative value to have an effect.
1117         establishedHeadroom := int64(t.maxEstablishedConns - len(t.conns))
1118         extraIncoming := int64(t.numReceivedConns() - t.maxEstablishedConns/2)
1119         // We want to allow some experimentation with new peers, and to try to
1120         // upset an oversupply of received connections.
1121         return int(min(max(5, extraIncoming)+establishedHeadroom, int64(t.cl.config.HalfOpenConnsPerTorrent)))
1122 }
1123
1124 func (t *Torrent) openNewConns() (initiated int) {
1125         defer t.updateWantPeersEvent()
1126         for t.peers.Len() != 0 {
1127                 if !t.wantConns() {
1128                         return
1129                 }
1130                 if len(t.halfOpen) >= t.maxHalfOpen() {
1131                         return
1132                 }
1133                 if len(t.cl.dialers) == 0 {
1134                         return
1135                 }
1136                 if t.cl.numHalfOpen >= t.cl.config.TotalHalfOpenConns {
1137                         return
1138                 }
1139                 p := t.peers.PopMax()
1140                 t.initiateConn(p)
1141                 initiated++
1142         }
1143         return
1144 }
1145
1146 func (t *Torrent) getConnPieceInclination() []int {
1147         _ret := t.connPieceInclinationPool.Get()
1148         if _ret == nil {
1149                 pieceInclinationsNew.Add(1)
1150                 return rand.Perm(int(t.numPieces()))
1151         }
1152         pieceInclinationsReused.Add(1)
1153         return *_ret.(*[]int)
1154 }
1155
1156 func (t *Torrent) putPieceInclination(pi []int) {
1157         t.connPieceInclinationPool.Put(&pi)
1158         pieceInclinationsPut.Add(1)
1159 }
1160
1161 func (t *Torrent) updatePieceCompletion(piece pieceIndex) bool {
1162         p := t.piece(piece)
1163         uncached := t.pieceCompleteUncached(piece)
1164         cached := p.completion()
1165         changed := cached != uncached
1166         complete := uncached.Complete
1167         p.storageCompletionOk = uncached.Ok
1168         t._completedPieces.Set(bitmap.BitIndex(piece), complete)
1169         if complete && len(p.dirtiers) != 0 {
1170                 t.logger.Printf("marked piece %v complete but still has dirtiers", piece)
1171         }
1172         if changed {
1173                 log.Fstr("piece %d completion changed: %+v -> %+v", piece, cached, uncached).SetLevel(log.Debug).Log(t.logger)
1174                 t.pieceCompletionChanged(piece)
1175         }
1176         return changed
1177 }
1178
1179 // Non-blocking read. Client lock is not required.
1180 func (t *Torrent) readAt(b []byte, off int64) (n int, err error) {
1181         for len(b) != 0 {
1182                 p := &t.pieces[off/t.info.PieceLength]
1183                 p.waitNoPendingWrites()
1184                 var n1 int
1185                 n1, err = p.Storage().ReadAt(b, off-p.Info().Offset())
1186                 if n1 == 0 {
1187                         break
1188                 }
1189                 off += int64(n1)
1190                 n += n1
1191                 b = b[n1:]
1192         }
1193         return
1194 }
1195
1196 // Returns an error if the metadata was completed, but couldn't be set for
1197 // some reason. Blame it on the last peer to contribute.
1198 func (t *Torrent) maybeCompleteMetadata() error {
1199         if t.haveInfo() {
1200                 // Nothing to do.
1201                 return nil
1202         }
1203         if !t.haveAllMetadataPieces() {
1204                 // Don't have enough metadata pieces.
1205                 return nil
1206         }
1207         err := t.setInfoBytes(t.metadataBytes)
1208         if err != nil {
1209                 t.invalidateMetadata()
1210                 return fmt.Errorf("error setting info bytes: %s", err)
1211         }
1212         if t.cl.config.Debug {
1213                 t.logger.Printf("%s: got metadata from peers", t)
1214         }
1215         return nil
1216 }
1217
1218 func (t *Torrent) readerPiecePriorities() (now, readahead bitmap.Bitmap) {
1219         t.forReaderOffsetPieces(func(begin, end pieceIndex) bool {
1220                 if end > begin {
1221                         now.Add(bitmap.BitIndex(begin))
1222                         readahead.AddRange(bitmap.BitIndex(begin)+1, bitmap.BitIndex(end))
1223                 }
1224                 return true
1225         })
1226         return
1227 }
1228
1229 func (t *Torrent) needData() bool {
1230         if t.closed.IsSet() {
1231                 return false
1232         }
1233         if !t.haveInfo() {
1234                 return true
1235         }
1236         return t._pendingPieces.Len() != 0
1237 }
1238
1239 func appendMissingStrings(old, new []string) (ret []string) {
1240         ret = old
1241 new:
1242         for _, n := range new {
1243                 for _, o := range old {
1244                         if o == n {
1245                                 continue new
1246                         }
1247                 }
1248                 ret = append(ret, n)
1249         }
1250         return
1251 }
1252
1253 func appendMissingTrackerTiers(existing [][]string, minNumTiers int) (ret [][]string) {
1254         ret = existing
1255         for minNumTiers > len(ret) {
1256                 ret = append(ret, nil)
1257         }
1258         return
1259 }
1260
1261 func (t *Torrent) addTrackers(announceList [][]string) {
1262         fullAnnounceList := &t.metainfo.AnnounceList
1263         t.metainfo.AnnounceList = appendMissingTrackerTiers(*fullAnnounceList, len(announceList))
1264         for tierIndex, trackerURLs := range announceList {
1265                 (*fullAnnounceList)[tierIndex] = appendMissingStrings((*fullAnnounceList)[tierIndex], trackerURLs)
1266         }
1267         t.startMissingTrackerScrapers()
1268         t.updateWantPeersEvent()
1269 }
1270
1271 // Don't call this before the info is available.
1272 func (t *Torrent) bytesCompleted() int64 {
1273         if !t.haveInfo() {
1274                 return 0
1275         }
1276         return t.info.TotalLength() - t.bytesLeft()
1277 }
1278
1279 func (t *Torrent) SetInfoBytes(b []byte) (err error) {
1280         t.cl.lock()
1281         defer t.cl.unlock()
1282         return t.setInfoBytes(b)
1283 }
1284
1285 // Returns true if connection is removed from torrent.Conns.
1286 func (t *Torrent) deleteConnection(c *PeerConn) (ret bool) {
1287         if !c.closed.IsSet() {
1288                 panic("connection is not closed")
1289                 // There are behaviours prevented by the closed state that will fail
1290                 // if the connection has been deleted.
1291         }
1292         _, ret = t.conns[c]
1293         delete(t.conns, c)
1294         // Avoid adding a drop event more than once. Probably we should track whether we've generated
1295         // the drop event against the PexConnState instead.
1296         if ret {
1297                 if !t.cl.config.DisablePEX {
1298                         t.pex.Drop(c)
1299                 }
1300         }
1301         torrent.Add("deleted connections", 1)
1302         c.deleteAllRequests()
1303         if t.numActivePeers() == 0 {
1304                 t.assertNoPendingRequests()
1305         }
1306         return
1307 }
1308
1309 func (t *Torrent) numActivePeers() (num int) {
1310         t.iterPeers(func(*Peer) {
1311                 num++
1312         })
1313         return
1314 }
1315
1316 func (t *Torrent) assertNoPendingRequests() {
1317         if len(t.pendingRequests) != 0 {
1318                 panic(t.pendingRequests)
1319         }
1320         //if len(t.lastRequested) != 0 {
1321         //      panic(t.lastRequested)
1322         //}
1323 }
1324
1325 func (t *Torrent) dropConnection(c *PeerConn) {
1326         t.cl.event.Broadcast()
1327         c.close()
1328         if t.deleteConnection(c) {
1329                 t.openNewConns()
1330         }
1331 }
1332
1333 func (t *Torrent) wantPeers() bool {
1334         if t.closed.IsSet() {
1335                 return false
1336         }
1337         if t.peers.Len() > t.cl.config.TorrentPeersLowWater {
1338                 return false
1339         }
1340         return t.needData() || t.seeding()
1341 }
1342
1343 func (t *Torrent) updateWantPeersEvent() {
1344         if t.wantPeers() {
1345                 t.wantPeersEvent.Set()
1346         } else {
1347                 t.wantPeersEvent.Clear()
1348         }
1349 }
1350
1351 // Returns whether the client should make effort to seed the torrent.
1352 func (t *Torrent) seeding() bool {
1353         cl := t.cl
1354         if t.closed.IsSet() {
1355                 return false
1356         }
1357         if t.dataUploadDisallowed {
1358                 return false
1359         }
1360         if cl.config.NoUpload {
1361                 return false
1362         }
1363         if !cl.config.Seed {
1364                 return false
1365         }
1366         if cl.config.DisableAggressiveUpload && t.needData() {
1367                 return false
1368         }
1369         return true
1370 }
1371
1372 func (t *Torrent) onWebRtcConn(
1373         c datachannel.ReadWriteCloser,
1374         dcc webtorrent.DataChannelContext,
1375 ) {
1376         defer c.Close()
1377         pc, err := t.cl.initiateProtocolHandshakes(
1378                 context.Background(),
1379                 webrtcNetConn{c, dcc},
1380                 t,
1381                 dcc.LocalOffered,
1382                 false,
1383                 webrtcNetAddr{dcc.Remote},
1384                 webrtcNetwork,
1385                 fmt.Sprintf("webrtc offer_id %x", dcc.OfferId),
1386         )
1387         if err != nil {
1388                 t.logger.WithDefaultLevel(log.Error).Printf("error in handshaking webrtc connection: %v", err)
1389                 return
1390         }
1391         if dcc.LocalOffered {
1392                 pc.Discovery = PeerSourceTracker
1393         } else {
1394                 pc.Discovery = PeerSourceIncoming
1395         }
1396         t.cl.lock()
1397         defer t.cl.unlock()
1398         err = t.cl.runHandshookConn(pc, t)
1399         if err != nil {
1400                 t.logger.WithDefaultLevel(log.Critical).Printf("error running handshook webrtc conn: %v", err)
1401         }
1402 }
1403
1404 func (t *Torrent) logRunHandshookConn(pc *PeerConn, logAll bool, level log.Level) {
1405         err := t.cl.runHandshookConn(pc, t)
1406         if err != nil || logAll {
1407                 t.logger.WithDefaultLevel(level).Printf("error running handshook conn: %v", err)
1408         }
1409 }
1410
1411 func (t *Torrent) runHandshookConnLoggingErr(pc *PeerConn) {
1412         t.logRunHandshookConn(pc, false, log.Debug)
1413 }
1414
1415 func (t *Torrent) startWebsocketAnnouncer(u url.URL) torrentTrackerAnnouncer {
1416         wtc, release := t.cl.websocketTrackers.Get(u.String())
1417         go func() {
1418                 <-t.closed.LockedChan(t.cl.locker())
1419                 release()
1420         }()
1421         wst := websocketTrackerStatus{u, wtc}
1422         go func() {
1423                 err := wtc.Announce(tracker.Started, t.infoHash)
1424                 if err != nil {
1425                         t.logger.WithDefaultLevel(log.Warning).Printf(
1426                                 "error in initial announce to %q: %v",
1427                                 u.String(), err,
1428                         )
1429                 }
1430         }()
1431         return wst
1432
1433 }
1434
1435 func (t *Torrent) startScrapingTracker(_url string) {
1436         if _url == "" {
1437                 return
1438         }
1439         u, err := url.Parse(_url)
1440         if err != nil {
1441                 // URLs with a leading '*' appear to be a uTorrent convention to
1442                 // disable trackers.
1443                 if _url[0] != '*' {
1444                         log.Str("error parsing tracker url").AddValues("url", _url).Log(t.logger)
1445                 }
1446                 return
1447         }
1448         if u.Scheme == "udp" {
1449                 u.Scheme = "udp4"
1450                 t.startScrapingTracker(u.String())
1451                 u.Scheme = "udp6"
1452                 t.startScrapingTracker(u.String())
1453                 return
1454         }
1455         if _, ok := t.trackerAnnouncers[_url]; ok {
1456                 return
1457         }
1458         sl := func() torrentTrackerAnnouncer {
1459                 switch u.Scheme {
1460                 case "ws", "wss":
1461                         if t.cl.config.DisableWebtorrent {
1462                                 return nil
1463                         }
1464                         return t.startWebsocketAnnouncer(*u)
1465                 case "udp4":
1466                         if t.cl.config.DisableIPv4Peers || t.cl.config.DisableIPv4 {
1467                                 return nil
1468                         }
1469                 case "udp6":
1470                         if t.cl.config.DisableIPv6 {
1471                                 return nil
1472                         }
1473                 }
1474                 newAnnouncer := &trackerScraper{
1475                         u: *u,
1476                         t: t,
1477                 }
1478                 go newAnnouncer.Run()
1479                 return newAnnouncer
1480         }()
1481         if sl == nil {
1482                 return
1483         }
1484         if t.trackerAnnouncers == nil {
1485                 t.trackerAnnouncers = make(map[string]torrentTrackerAnnouncer)
1486         }
1487         t.trackerAnnouncers[_url] = sl
1488 }
1489
1490 // Adds and starts tracker scrapers for tracker URLs that aren't already
1491 // running.
1492 func (t *Torrent) startMissingTrackerScrapers() {
1493         if t.cl.config.DisableTrackers {
1494                 return
1495         }
1496         t.startScrapingTracker(t.metainfo.Announce)
1497         for _, tier := range t.metainfo.AnnounceList {
1498                 for _, url := range tier {
1499                         t.startScrapingTracker(url)
1500                 }
1501         }
1502 }
1503
1504 // Returns an AnnounceRequest with fields filled out to defaults and current
1505 // values.
1506 func (t *Torrent) announceRequest(event tracker.AnnounceEvent) tracker.AnnounceRequest {
1507         // Note that IPAddress is not set. It's set for UDP inside the tracker code, since it's
1508         // dependent on the network in use.
1509         return tracker.AnnounceRequest{
1510                 Event: event,
1511                 NumWant: func() int32 {
1512                         if t.wantPeers() && len(t.cl.dialers) > 0 {
1513                                 return -1
1514                         } else {
1515                                 return 0
1516                         }
1517                 }(),
1518                 Port:     uint16(t.cl.incomingPeerPort()),
1519                 PeerId:   t.cl.peerID,
1520                 InfoHash: t.infoHash,
1521                 Key:      t.cl.announceKey(),
1522
1523                 // The following are vaguely described in BEP 3.
1524
1525                 Left:     t.bytesLeftAnnounce(),
1526                 Uploaded: t.stats.BytesWrittenData.Int64(),
1527                 // There's no mention of wasted or unwanted download in the BEP.
1528                 Downloaded: t.stats.BytesReadUsefulData.Int64(),
1529         }
1530 }
1531
1532 // Adds peers revealed in an announce until the announce ends, or we have
1533 // enough peers.
1534 func (t *Torrent) consumeDhtAnnouncePeers(pvs <-chan dht.PeersValues) {
1535         cl := t.cl
1536         for v := range pvs {
1537                 cl.lock()
1538                 for _, cp := range v.Peers {
1539                         if cp.Port == 0 {
1540                                 // Can't do anything with this.
1541                                 continue
1542                         }
1543                         t.addPeer(PeerInfo{
1544                                 Addr:   ipPortAddr{cp.IP, cp.Port},
1545                                 Source: PeerSourceDhtGetPeers,
1546                         })
1547                 }
1548                 cl.unlock()
1549         }
1550 }
1551
1552 func (t *Torrent) announceToDht(impliedPort bool, s DhtServer) error {
1553         ps, err := s.Announce(t.infoHash, t.cl.incomingPeerPort(), impliedPort)
1554         if err != nil {
1555                 return err
1556         }
1557         go t.consumeDhtAnnouncePeers(ps.Peers())
1558         select {
1559         case <-t.closed.LockedChan(t.cl.locker()):
1560         case <-time.After(5 * time.Minute):
1561         }
1562         ps.Close()
1563         return nil
1564 }
1565
1566 func (t *Torrent) dhtAnnouncer(s DhtServer) {
1567         cl := t.cl
1568         cl.lock()
1569         defer cl.unlock()
1570         for {
1571                 for {
1572                         if t.closed.IsSet() {
1573                                 return
1574                         }
1575                         if !t.wantPeers() {
1576                                 goto wait
1577                         }
1578                         // TODO: Determine if there's a listener on the port we're announcing.
1579                         if len(cl.dialers) == 0 && len(cl.listeners) == 0 {
1580                                 goto wait
1581                         }
1582                         break
1583                 wait:
1584                         cl.event.Wait()
1585                 }
1586                 func() {
1587                         t.numDHTAnnounces++
1588                         cl.unlock()
1589                         defer cl.lock()
1590                         err := t.announceToDht(true, s)
1591                         if err != nil {
1592                                 t.logger.WithDefaultLevel(log.Warning).Printf("error announcing %q to DHT: %s", t, err)
1593                         }
1594                 }()
1595         }
1596 }
1597
1598 func (t *Torrent) addPeers(peers []PeerInfo) (added int) {
1599         for _, p := range peers {
1600                 if t.addPeer(p) {
1601                         added++
1602                 }
1603         }
1604         return
1605 }
1606
1607 // The returned TorrentStats may require alignment in memory. See
1608 // https://github.com/anacrolix/torrent/issues/383.
1609 func (t *Torrent) Stats() TorrentStats {
1610         t.cl.rLock()
1611         defer t.cl.rUnlock()
1612         return t.statsLocked()
1613 }
1614
1615 func (t *Torrent) statsLocked() (ret TorrentStats) {
1616         ret.ActivePeers = len(t.conns)
1617         ret.HalfOpenPeers = len(t.halfOpen)
1618         ret.PendingPeers = t.peers.Len()
1619         ret.TotalPeers = t.numTotalPeers()
1620         ret.ConnectedSeeders = 0
1621         for c := range t.conns {
1622                 if all, ok := c.peerHasAllPieces(); all && ok {
1623                         ret.ConnectedSeeders++
1624                 }
1625         }
1626         ret.ConnStats = t.stats.Copy()
1627         return
1628 }
1629
1630 // The total number of peers in the torrent.
1631 func (t *Torrent) numTotalPeers() int {
1632         peers := make(map[string]struct{})
1633         for conn := range t.conns {
1634                 ra := conn.conn.RemoteAddr()
1635                 if ra == nil {
1636                         // It's been closed and doesn't support RemoteAddr.
1637                         continue
1638                 }
1639                 peers[ra.String()] = struct{}{}
1640         }
1641         for addr := range t.halfOpen {
1642                 peers[addr] = struct{}{}
1643         }
1644         t.peers.Each(func(peer PeerInfo) {
1645                 peers[peer.Addr.String()] = struct{}{}
1646         })
1647         return len(peers)
1648 }
1649
1650 // Reconcile bytes transferred before connection was associated with a
1651 // torrent.
1652 func (t *Torrent) reconcileHandshakeStats(c *PeerConn) {
1653         if c._stats != (ConnStats{
1654                 // Handshakes should only increment these fields:
1655                 BytesWritten: c._stats.BytesWritten,
1656                 BytesRead:    c._stats.BytesRead,
1657         }) {
1658                 panic("bad stats")
1659         }
1660         c.postHandshakeStats(func(cs *ConnStats) {
1661                 cs.BytesRead.Add(c._stats.BytesRead.Int64())
1662                 cs.BytesWritten.Add(c._stats.BytesWritten.Int64())
1663         })
1664         c.reconciledHandshakeStats = true
1665 }
1666
1667 // Returns true if the connection is added.
1668 func (t *Torrent) addConnection(c *PeerConn) (err error) {
1669         defer func() {
1670                 if err == nil {
1671                         torrent.Add("added connections", 1)
1672                 }
1673         }()
1674         if t.closed.IsSet() {
1675                 return errors.New("torrent closed")
1676         }
1677         for c0 := range t.conns {
1678                 if c.PeerID != c0.PeerID {
1679                         continue
1680                 }
1681                 if !t.cl.config.DropDuplicatePeerIds {
1682                         continue
1683                 }
1684                 if left, ok := c.hasPreferredNetworkOver(c0); ok && left {
1685                         c0.close()
1686                         t.deleteConnection(c0)
1687                 } else {
1688                         return errors.New("existing connection preferred")
1689                 }
1690         }
1691         if len(t.conns) >= t.maxEstablishedConns {
1692                 c := t.worstBadConn()
1693                 if c == nil {
1694                         return errors.New("don't want conns")
1695                 }
1696                 c.close()
1697                 t.deleteConnection(c)
1698         }
1699         if len(t.conns) >= t.maxEstablishedConns {
1700                 panic(len(t.conns))
1701         }
1702         t.conns[c] = struct{}{}
1703         if !t.cl.config.DisablePEX && !c.PeerExtensionBytes.SupportsExtended() {
1704                 t.pex.Add(c) // as no further extended handshake expected
1705         }
1706         return nil
1707 }
1708
1709 func (t *Torrent) wantConns() bool {
1710         if !t.networkingEnabled {
1711                 return false
1712         }
1713         if t.closed.IsSet() {
1714                 return false
1715         }
1716         if !t.seeding() && !t.needData() {
1717                 return false
1718         }
1719         if len(t.conns) < t.maxEstablishedConns {
1720                 return true
1721         }
1722         return t.worstBadConn() != nil
1723 }
1724
1725 func (t *Torrent) SetMaxEstablishedConns(max int) (oldMax int) {
1726         t.cl.lock()
1727         defer t.cl.unlock()
1728         oldMax = t.maxEstablishedConns
1729         t.maxEstablishedConns = max
1730         wcs := slices.HeapInterface(slices.FromMapKeys(t.conns), func(l, r *PeerConn) bool {
1731                 return worseConn(&l.Peer, &r.Peer)
1732         })
1733         for len(t.conns) > t.maxEstablishedConns && wcs.Len() > 0 {
1734                 t.dropConnection(wcs.Pop().(*PeerConn))
1735         }
1736         t.openNewConns()
1737         return oldMax
1738 }
1739
1740 func (t *Torrent) pieceHashed(piece pieceIndex, passed bool, hashIoErr error) {
1741         t.logger.Log(log.Fstr("hashed piece %d (passed=%t)", piece, passed).SetLevel(log.Debug))
1742         p := t.piece(piece)
1743         p.numVerifies++
1744         t.cl.event.Broadcast()
1745         if t.closed.IsSet() {
1746                 return
1747         }
1748
1749         // Don't score the first time a piece is hashed, it could be an initial check.
1750         if p.storageCompletionOk {
1751                 if passed {
1752                         pieceHashedCorrect.Add(1)
1753                 } else {
1754                         log.Fmsg("piece %d failed hash: %d connections contributed", piece, len(p.dirtiers)).AddValues(t, p).Log(t.logger)
1755                         pieceHashedNotCorrect.Add(1)
1756                 }
1757         }
1758
1759         p.marking = true
1760         t.publishPieceChange(piece)
1761         defer func() {
1762                 p.marking = false
1763                 t.publishPieceChange(piece)
1764         }()
1765
1766         if passed {
1767                 if len(p.dirtiers) != 0 {
1768                         // Don't increment stats above connection-level for every involved connection.
1769                         t.allStats((*ConnStats).incrementPiecesDirtiedGood)
1770                 }
1771                 for c := range p.dirtiers {
1772                         c._stats.incrementPiecesDirtiedGood()
1773                 }
1774                 t.clearPieceTouchers(piece)
1775                 t.cl.unlock()
1776                 err := p.Storage().MarkComplete()
1777                 if err != nil {
1778                         t.logger.Printf("%T: error marking piece complete %d: %s", t.storage, piece, err)
1779                 }
1780                 t.cl.lock()
1781
1782                 if t.closed.IsSet() {
1783                         return
1784                 }
1785                 t.pendAllChunkSpecs(piece)
1786         } else {
1787                 if len(p.dirtiers) != 0 && p.allChunksDirty() && hashIoErr == nil {
1788                         // Peers contributed to all the data for this piece hash failure, and the failure was
1789                         // not due to errors in the storage (such as data being dropped in a cache).
1790
1791                         // Increment Torrent and above stats, and then specific connections.
1792                         t.allStats((*ConnStats).incrementPiecesDirtiedBad)
1793                         for c := range p.dirtiers {
1794                                 // Y u do dis peer?!
1795                                 c.stats().incrementPiecesDirtiedBad()
1796                         }
1797
1798                         bannableTouchers := make([]*Peer, 0, len(p.dirtiers))
1799                         for c := range p.dirtiers {
1800                                 if !c.trusted {
1801                                         bannableTouchers = append(bannableTouchers, c)
1802                                 }
1803                         }
1804                         t.clearPieceTouchers(piece)
1805                         slices.Sort(bannableTouchers, connLessTrusted)
1806
1807                         if t.cl.config.Debug {
1808                                 t.logger.Printf(
1809                                         "bannable conns by trust for piece %d: %v",
1810                                         piece,
1811                                         func() (ret []connectionTrust) {
1812                                                 for _, c := range bannableTouchers {
1813                                                         ret = append(ret, c.trust())
1814                                                 }
1815                                                 return
1816                                         }(),
1817                                 )
1818                         }
1819
1820                         if len(bannableTouchers) >= 1 {
1821                                 c := bannableTouchers[0]
1822                                 t.cl.banPeerIP(c.remoteIp())
1823                                 c.drop()
1824                         }
1825                 }
1826                 t.onIncompletePiece(piece)
1827                 p.Storage().MarkNotComplete()
1828         }
1829         t.updatePieceCompletion(piece)
1830 }
1831
1832 func (t *Torrent) cancelRequestsForPiece(piece pieceIndex) {
1833         // TODO: Make faster
1834         for cn := range t.conns {
1835                 cn.tickleWriter()
1836         }
1837 }
1838
1839 func (t *Torrent) onPieceCompleted(piece pieceIndex) {
1840         t.pendAllChunkSpecs(piece)
1841         t.cancelRequestsForPiece(piece)
1842         for conn := range t.conns {
1843                 conn.have(piece)
1844                 t.maybeDropMutuallyCompletePeer(&conn.Peer)
1845         }
1846 }
1847
1848 // Called when a piece is found to be not complete.
1849 func (t *Torrent) onIncompletePiece(piece pieceIndex) {
1850         if t.pieceAllDirty(piece) {
1851                 t.pendAllChunkSpecs(piece)
1852         }
1853         if !t.wantPieceIndex(piece) {
1854                 // t.logger.Printf("piece %d incomplete and unwanted", piece)
1855                 return
1856         }
1857         // We could drop any connections that we told we have a piece that we
1858         // don't here. But there's a test failure, and it seems clients don't care
1859         // if you request pieces that you already claim to have. Pruning bad
1860         // connections might just remove any connections that aren't treating us
1861         // favourably anyway.
1862
1863         // for c := range t.conns {
1864         //      if c.sentHave(piece) {
1865         //              c.drop()
1866         //      }
1867         // }
1868         t.iterPeers(func(conn *Peer) {
1869                 if conn.peerHasPiece(piece) {
1870                         conn.updateRequests()
1871                 }
1872         })
1873 }
1874
1875 func (t *Torrent) tryCreateMorePieceHashers() {
1876         for !t.closed.IsSet() && t.activePieceHashes < 2 && t.tryCreatePieceHasher() {
1877         }
1878 }
1879
1880 func (t *Torrent) tryCreatePieceHasher() bool {
1881         if t.storage == nil {
1882                 return false
1883         }
1884         pi, ok := t.getPieceToHash()
1885         if !ok {
1886                 return false
1887         }
1888         p := t.piece(pi)
1889         t.piecesQueuedForHash.Remove(pi)
1890         p.hashing = true
1891         t.publishPieceChange(pi)
1892         t.updatePiecePriority(pi)
1893         t.storageLock.RLock()
1894         t.activePieceHashes++
1895         go t.pieceHasher(pi)
1896         return true
1897 }
1898
1899 func (t *Torrent) getPieceToHash() (ret pieceIndex, ok bool) {
1900         t.piecesQueuedForHash.IterTyped(func(i pieceIndex) bool {
1901                 if t.piece(i).hashing {
1902                         return true
1903                 }
1904                 ret = i
1905                 ok = true
1906                 return false
1907         })
1908         return
1909 }
1910
1911 func (t *Torrent) pieceHasher(index pieceIndex) {
1912         p := t.piece(index)
1913         sum, copyErr := t.hashPiece(index)
1914         correct := sum == *p.hash
1915         switch copyErr {
1916         case nil, io.EOF:
1917         default:
1918                 log.Fmsg("piece %v (%s) hash failure copy error: %v", p, p.hash.HexString(), copyErr).Log(t.logger)
1919         }
1920         t.storageLock.RUnlock()
1921         t.cl.lock()
1922         defer t.cl.unlock()
1923         p.hashing = false
1924         t.updatePiecePriority(index)
1925         t.pieceHashed(index, correct, copyErr)
1926         t.publishPieceChange(index)
1927         t.activePieceHashes--
1928         t.tryCreateMorePieceHashers()
1929 }
1930
1931 // Return the connections that touched a piece, and clear the entries while doing it.
1932 func (t *Torrent) clearPieceTouchers(pi pieceIndex) {
1933         p := t.piece(pi)
1934         for c := range p.dirtiers {
1935                 delete(c.peerTouchedPieces, pi)
1936                 delete(p.dirtiers, c)
1937         }
1938 }
1939
1940 func (t *Torrent) peersAsSlice() (ret []*Peer) {
1941         t.iterPeers(func(p *Peer) {
1942                 ret = append(ret, p)
1943         })
1944         return
1945 }
1946
1947 func (t *Torrent) queuePieceCheck(pieceIndex pieceIndex) {
1948         piece := t.piece(pieceIndex)
1949         if piece.queuedForHash() {
1950                 return
1951         }
1952         t.piecesQueuedForHash.Add(bitmap.BitIndex(pieceIndex))
1953         t.publishPieceChange(pieceIndex)
1954         t.updatePiecePriority(pieceIndex)
1955         t.tryCreateMorePieceHashers()
1956 }
1957
1958 // Forces all the pieces to be re-hashed. See also Piece.VerifyData. This should not be called
1959 // before the Info is available.
1960 func (t *Torrent) VerifyData() {
1961         for i := pieceIndex(0); i < t.NumPieces(); i++ {
1962                 t.Piece(i).VerifyData()
1963         }
1964 }
1965
1966 // Start the process of connecting to the given peer for the given torrent if appropriate.
1967 func (t *Torrent) initiateConn(peer PeerInfo) {
1968         if peer.Id == t.cl.peerID {
1969                 return
1970         }
1971         if t.cl.badPeerAddr(peer.Addr) && !peer.Trusted {
1972                 return
1973         }
1974         addr := peer.Addr
1975         if t.addrActive(addr.String()) {
1976                 return
1977         }
1978         t.cl.numHalfOpen++
1979         t.halfOpen[addr.String()] = peer
1980         go t.cl.outgoingConnection(t, addr, peer.Source, peer.Trusted)
1981 }
1982
1983 // Adds a trusted, pending peer for each of the given Client's addresses. Typically used in tests to
1984 // quickly make one Client visible to the Torrent of another Client.
1985 func (t *Torrent) AddClientPeer(cl *Client) int {
1986         return t.AddPeers(func() (ps []PeerInfo) {
1987                 for _, la := range cl.ListenAddrs() {
1988                         ps = append(ps, PeerInfo{
1989                                 Addr:    la,
1990                                 Trusted: true,
1991                         })
1992                 }
1993                 return
1994         }())
1995 }
1996
1997 // All stats that include this Torrent. Useful when we want to increment ConnStats but not for every
1998 // connection.
1999 func (t *Torrent) allStats(f func(*ConnStats)) {
2000         f(&t.stats)
2001         f(&t.cl.stats)
2002 }
2003
2004 func (t *Torrent) hashingPiece(i pieceIndex) bool {
2005         return t.pieces[i].hashing
2006 }
2007
2008 func (t *Torrent) pieceQueuedForHash(i pieceIndex) bool {
2009         return t.piecesQueuedForHash.Get(bitmap.BitIndex(i))
2010 }
2011
2012 func (t *Torrent) dialTimeout() time.Duration {
2013         return reducedDialTimeout(t.cl.config.MinDialTimeout, t.cl.config.NominalDialTimeout, t.cl.config.HalfOpenConnsPerTorrent, t.peers.Len())
2014 }
2015
2016 func (t *Torrent) piece(i int) *Piece {
2017         return &t.pieces[i]
2018 }
2019
2020 func (t *Torrent) requestStrategyTorrent() requestStrategyTorrent {
2021         return t
2022 }
2023
2024 type torrentRequestStrategyCallbacks struct {
2025         t *Torrent
2026 }
2027
2028 func (cb torrentRequestStrategyCallbacks) requestTimedOut(r Request) {
2029         torrent.Add("Request timeouts", 1)
2030         cb.t.cl.lock()
2031         defer cb.t.cl.unlock()
2032         cb.t.iterPeers(func(cn *Peer) {
2033                 if cn.peerHasPiece(pieceIndex(r.Index)) {
2034                         cn.updateRequests()
2035                 }
2036         })
2037
2038 }
2039
2040 func (t *Torrent) requestStrategyCallbacks() requestStrategyCallbacks {
2041         return torrentRequestStrategyCallbacks{t}
2042 }
2043
2044 func (t *Torrent) onWriteChunkErr(err error) {
2045         if t.userOnWriteChunkErr != nil {
2046                 go t.userOnWriteChunkErr(err)
2047                 return
2048         }
2049         t.logger.WithDefaultLevel(log.Critical).Printf("default chunk write error handler: disabling data download")
2050         t.disallowDataDownloadLocked()
2051 }
2052
2053 func (t *Torrent) DisallowDataDownload() {
2054         t.cl.lock()
2055         defer t.cl.unlock()
2056         t.disallowDataDownloadLocked()
2057 }
2058
2059 func (t *Torrent) disallowDataDownloadLocked() {
2060         t.dataDownloadDisallowed = true
2061         t.iterPeers(func(c *Peer) {
2062                 c.updateRequests()
2063         })
2064         t.tickleReaders()
2065 }
2066
2067 func (t *Torrent) AllowDataDownload() {
2068         t.cl.lock()
2069         defer t.cl.unlock()
2070         t.dataDownloadDisallowed = false
2071         t.tickleReaders()
2072         t.iterPeers(func(c *Peer) {
2073                 c.updateRequests()
2074         })
2075 }
2076
2077 // Enables uploading data, if it was disabled.
2078 func (t *Torrent) AllowDataUpload() {
2079         t.cl.lock()
2080         defer t.cl.unlock()
2081         t.dataUploadDisallowed = false
2082         for c := range t.conns {
2083                 c.updateRequests()
2084         }
2085 }
2086
2087 // Disables uploading data, if it was enabled.
2088 func (t *Torrent) DisallowDataUpload() {
2089         t.cl.lock()
2090         defer t.cl.unlock()
2091         t.dataUploadDisallowed = true
2092         for c := range t.conns {
2093                 c.updateRequests()
2094         }
2095 }
2096
2097 // Sets a handler that is called if there's an error writing a chunk to local storage. By default,
2098 // or if nil, a critical message is logged, and data download is disabled.
2099 func (t *Torrent) SetOnWriteChunkError(f func(error)) {
2100         t.cl.lock()
2101         defer t.cl.unlock()
2102         t.userOnWriteChunkErr = f
2103 }
2104
2105 func (t *Torrent) iterPeers(f func(*Peer)) {
2106         for pc := range t.conns {
2107                 f(&pc.Peer)
2108         }
2109         for _, ws := range t.webSeeds {
2110                 f(ws)
2111         }
2112 }
2113
2114 func (t *Torrent) callbacks() *Callbacks {
2115         return &t.cl.config.Callbacks
2116 }
2117
2118 var WebseedHttpClient = &http.Client{
2119         Transport: &http.Transport{
2120                 MaxConnsPerHost: 10,
2121         },
2122 }
2123
2124 func (t *Torrent) addWebSeed(url string) {
2125         if t.cl.config.DisableWebseeds {
2126                 return
2127         }
2128         if _, ok := t.webSeeds[url]; ok {
2129                 return
2130         }
2131         const maxRequests = 10
2132         ws := webseedPeer{
2133                 peer: Peer{
2134                         t:                        t,
2135                         outgoing:                 true,
2136                         Network:                  "http",
2137                         reconciledHandshakeStats: true,
2138                         peerSentHaveAll:          true,
2139                         // TODO: Raise this limit, and instead limit concurrent fetches.
2140                         PeerMaxRequests: 32,
2141                         RemoteAddr:      remoteAddrFromUrl(url),
2142                         callbacks:       t.callbacks(),
2143                 },
2144                 client: webseed.Client{
2145                         // Consider a MaxConnsPerHost in the transport for this, possibly in a global Client.
2146                         HttpClient: WebseedHttpClient,
2147                         Url:        url,
2148                 },
2149                 activeRequests: make(map[Request]webseed.Request, maxRequests),
2150         }
2151         ws.requesterCond.L = t.cl.locker()
2152         for range iter.N(maxRequests) {
2153                 go ws.requester()
2154         }
2155         for _, f := range t.callbacks().NewPeer {
2156                 f(&ws.peer)
2157         }
2158         ws.peer.logger = t.logger.WithContextValue(&ws)
2159         ws.peer.peerImpl = &ws
2160         if t.haveInfo() {
2161                 ws.onGotInfo(t.info)
2162         }
2163         t.webSeeds[url] = &ws.peer
2164 }
2165
2166 func (t *Torrent) peerIsActive(p *Peer) (active bool) {
2167         t.iterPeers(func(p1 *Peer) {
2168                 if p1 == p {
2169                         active = true
2170                 }
2171         })
2172         return
2173 }