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