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