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