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