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