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