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