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