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