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