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