]> Sergey Matveev's repositories - btrtrc.git/blob - torrent.go
Disable data downloading on storage write errors
[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 []PieceStateRun) {
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 pieceStateRunStatusChars(psr PieceStateRun) (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.Fprint(w, "Piece States:")
580                 for _, psr := range t.pieceStateRuns() {
581                         w.Write([]byte(" "))
582                         w.Write([]byte(pieceStateRunStatusChars(psr)))
583                 }
584                 fmt.Fprintln(w)
585         }
586         fmt.Fprintf(w, "Reader Pieces:")
587         t.forReaderOffsetPieces(func(begin, end pieceIndex) (again bool) {
588                 fmt.Fprintf(w, " %d:%d", begin, end)
589                 return true
590         })
591         fmt.Fprintln(w)
592
593         fmt.Fprintf(w, "Enabled trackers:\n")
594         func() {
595                 tw := tabwriter.NewWriter(w, 0, 0, 2, ' ', 0)
596                 fmt.Fprintf(tw, "    URL\tNext announce\tLast announce\n")
597                 for _, ta := range slices.Sort(slices.FromMapElems(t.trackerAnnouncers), func(l, r *trackerScraper) bool {
598                         lu := l.u
599                         ru := r.u
600                         var luns, runs url.URL = lu, ru
601                         luns.Scheme = ""
602                         runs.Scheme = ""
603                         var ml missinggo.MultiLess
604                         ml.StrictNext(luns.String() == runs.String(), luns.String() < runs.String())
605                         ml.StrictNext(lu.String() == ru.String(), lu.String() < ru.String())
606                         return ml.Less()
607                 }).([]*trackerScraper) {
608                         fmt.Fprintf(tw, "    %s\n", ta.statusLine())
609                 }
610                 tw.Flush()
611         }()
612
613         fmt.Fprintf(w, "DHT Announces: %d\n", t.numDHTAnnounces)
614
615         spew.NewDefaultConfig()
616         spew.Fdump(w, t.statsLocked())
617
618         conns := t.connsAsSlice()
619         slices.Sort(conns, worseConn)
620         for i, c := range conns {
621                 fmt.Fprintf(w, "%2d. ", i+1)
622                 c.writeStatus(w, t)
623         }
624 }
625
626 func (t *Torrent) haveInfo() bool {
627         return t.info != nil
628 }
629
630 // Returns a run-time generated MetaInfo that includes the info bytes and
631 // announce-list as currently known to the client.
632 func (t *Torrent) newMetaInfo() metainfo.MetaInfo {
633         return metainfo.MetaInfo{
634                 CreationDate: time.Now().Unix(),
635                 Comment:      "dynamic metainfo from client",
636                 CreatedBy:    "go.torrent",
637                 AnnounceList: t.metainfo.UpvertedAnnounceList(),
638                 InfoBytes: func() []byte {
639                         if t.haveInfo() {
640                                 return t.metadataBytes
641                         } else {
642                                 return nil
643                         }
644                 }(),
645         }
646 }
647
648 func (t *Torrent) BytesMissing() int64 {
649         t.cl.rLock()
650         defer t.cl.rUnlock()
651         return t.bytesMissingLocked()
652 }
653
654 func (t *Torrent) bytesMissingLocked() int64 {
655         return t.bytesLeft()
656 }
657
658 func (t *Torrent) bytesLeft() (left int64) {
659         bitmap.Flip(t._completedPieces, 0, bitmap.BitIndex(t.numPieces())).IterTyped(func(piece int) bool {
660                 p := &t.pieces[piece]
661                 left += int64(p.length() - p.numDirtyBytes())
662                 return true
663         })
664         return
665 }
666
667 // Bytes left to give in tracker announces.
668 func (t *Torrent) bytesLeftAnnounce() int64 {
669         if t.haveInfo() {
670                 return t.bytesLeft()
671         } else {
672                 return -1
673         }
674 }
675
676 func (t *Torrent) piecePartiallyDownloaded(piece pieceIndex) bool {
677         if t.pieceComplete(piece) {
678                 return false
679         }
680         if t.pieceAllDirty(piece) {
681                 return false
682         }
683         return t.pieces[piece].hasDirtyChunks()
684 }
685
686 func (t *Torrent) usualPieceSize() int {
687         return int(t.info.PieceLength)
688 }
689
690 func (t *Torrent) numPieces() pieceIndex {
691         return pieceIndex(t.info.NumPieces())
692 }
693
694 func (t *Torrent) numPiecesCompleted() (num int) {
695         return t._completedPieces.Len()
696 }
697
698 func (t *Torrent) close() (err error) {
699         t.closed.Set()
700         t.tickleReaders()
701         if t.storage != nil {
702                 t.storageLock.Lock()
703                 t.storage.Close()
704                 t.storageLock.Unlock()
705         }
706         for conn := range t.conns {
707                 conn.close()
708         }
709         t.cl.event.Broadcast()
710         t.pieceStateChanges.Close()
711         t.updateWantPeersEvent()
712         return
713 }
714
715 func (t *Torrent) requestOffset(r request) int64 {
716         return torrentRequestOffset(*t.length, int64(t.usualPieceSize()), r)
717 }
718
719 // Return the request that would include the given offset into the torrent
720 // data. Returns !ok if there is no such request.
721 func (t *Torrent) offsetRequest(off int64) (req request, ok bool) {
722         return torrentOffsetRequest(*t.length, t.info.PieceLength, int64(t.chunkSize), off)
723 }
724
725 func (t *Torrent) writeChunk(piece int, begin int64, data []byte) (err error) {
726         defer perf.ScopeTimerErr(&err)()
727         n, err := t.pieces[piece].Storage().WriteAt(data, begin)
728         if err == nil && n != len(data) {
729                 err = io.ErrShortWrite
730         }
731         return err
732 }
733
734 func (t *Torrent) bitfield() (bf []bool) {
735         bf = make([]bool, t.numPieces())
736         t._completedPieces.IterTyped(func(piece int) (again bool) {
737                 bf[piece] = true
738                 return true
739         })
740         return
741 }
742
743 func (t *Torrent) pieceNumChunks(piece pieceIndex) pp.Integer {
744         return (t.pieceLength(piece) + t.chunkSize - 1) / t.chunkSize
745 }
746
747 func (t *Torrent) pendAllChunkSpecs(pieceIndex pieceIndex) {
748         t.pieces[pieceIndex]._dirtyChunks.Clear()
749 }
750
751 func (t *Torrent) pieceLength(piece pieceIndex) pp.Integer {
752         if t.info.PieceLength == 0 {
753                 // There will be no variance amongst pieces. Only pain.
754                 return 0
755         }
756         if piece == t.numPieces()-1 {
757                 ret := pp.Integer(*t.length % t.info.PieceLength)
758                 if ret != 0 {
759                         return ret
760                 }
761         }
762         return pp.Integer(t.info.PieceLength)
763 }
764
765 func (t *Torrent) hashPiece(piece pieceIndex) (ret metainfo.Hash, copyErr error) {
766         hash := pieceHash.New()
767         p := t.piece(piece)
768         p.waitNoPendingWrites()
769         ip := t.info.Piece(int(piece))
770         pl := ip.Length()
771         _, copyErr = io.CopyN( // Return no error iff pl bytes are copied.
772                 hash, io.NewSectionReader(t.pieces[piece].Storage(), 0, pl), pl)
773         missinggo.CopyExact(&ret, hash.Sum(nil))
774         return
775 }
776
777 func (t *Torrent) haveAnyPieces() bool {
778         return t._completedPieces.Len() != 0
779 }
780
781 func (t *Torrent) haveAllPieces() bool {
782         if !t.haveInfo() {
783                 return false
784         }
785         return t._completedPieces.Len() == bitmap.BitIndex(t.numPieces())
786 }
787
788 func (t *Torrent) havePiece(index pieceIndex) bool {
789         return t.haveInfo() && t.pieceComplete(index)
790 }
791
792 func (t *Torrent) haveChunk(r request) (ret bool) {
793         // defer func() {
794         //      log.Println("have chunk", r, ret)
795         // }()
796         if !t.haveInfo() {
797                 return false
798         }
799         if t.pieceComplete(pieceIndex(r.Index)) {
800                 return true
801         }
802         p := &t.pieces[r.Index]
803         return !p.pendingChunk(r.chunkSpec, t.chunkSize)
804 }
805
806 func chunkIndex(cs chunkSpec, chunkSize pp.Integer) int {
807         return int(cs.Begin / chunkSize)
808 }
809
810 func (t *Torrent) wantPieceIndex(index pieceIndex) bool {
811         if !t.haveInfo() {
812                 return false
813         }
814         if index < 0 || index >= t.numPieces() {
815                 return false
816         }
817         p := &t.pieces[index]
818         if p.queuedForHash() {
819                 return false
820         }
821         if p.hashing {
822                 return false
823         }
824         if t.pieceComplete(index) {
825                 return false
826         }
827         if t._pendingPieces.Contains(bitmap.BitIndex(index)) {
828                 return true
829         }
830         // t.logger.Printf("piece %d not pending", index)
831         return !t.forReaderOffsetPieces(func(begin, end pieceIndex) bool {
832                 return index < begin || index >= end
833         })
834 }
835
836 // The worst connection is one that hasn't been sent, or sent anything useful
837 // for the longest. A bad connection is one that usually sends us unwanted
838 // pieces, or has been in worser half of the established connections for more
839 // than a minute.
840 func (t *Torrent) worstBadConn() *PeerConn {
841         wcs := worseConnSlice{t.unclosedConnsAsSlice()}
842         heap.Init(&wcs)
843         for wcs.Len() != 0 {
844                 c := heap.Pop(&wcs).(*PeerConn)
845                 if c._stats.ChunksReadWasted.Int64() >= 6 && c._stats.ChunksReadWasted.Int64() > c._stats.ChunksReadUseful.Int64() {
846                         return c
847                 }
848                 // If the connection is in the worst half of the established
849                 // connection quota and is older than a minute.
850                 if wcs.Len() >= (t.maxEstablishedConns+1)/2 {
851                         // Give connections 1 minute to prove themselves.
852                         if time.Since(c.completedHandshake) > time.Minute {
853                                 return c
854                         }
855                 }
856         }
857         return nil
858 }
859
860 type PieceStateChange struct {
861         Index int
862         PieceState
863 }
864
865 func (t *Torrent) publishPieceChange(piece pieceIndex) {
866         t.cl._mu.Defer(func() {
867                 cur := t.pieceState(piece)
868                 p := &t.pieces[piece]
869                 if cur != p.publicPieceState {
870                         p.publicPieceState = cur
871                         t.pieceStateChanges.Publish(PieceStateChange{
872                                 int(piece),
873                                 cur,
874                         })
875                 }
876         })
877 }
878
879 func (t *Torrent) pieceNumPendingChunks(piece pieceIndex) pp.Integer {
880         if t.pieceComplete(piece) {
881                 return 0
882         }
883         return t.pieceNumChunks(piece) - t.pieces[piece].numDirtyChunks()
884 }
885
886 func (t *Torrent) pieceAllDirty(piece pieceIndex) bool {
887         return t.pieces[piece]._dirtyChunks.Len() == int(t.pieceNumChunks(piece))
888 }
889
890 func (t *Torrent) readersChanged() {
891         t.updateReaderPieces()
892         t.updateAllPiecePriorities()
893 }
894
895 func (t *Torrent) updateReaderPieces() {
896         t._readerNowPieces, t._readerReadaheadPieces = t.readerPiecePriorities()
897 }
898
899 func (t *Torrent) readerPosChanged(from, to pieceRange) {
900         if from == to {
901                 return
902         }
903         t.updateReaderPieces()
904         // Order the ranges, high and low.
905         l, h := from, to
906         if l.begin > h.begin {
907                 l, h = h, l
908         }
909         if l.end < h.begin {
910                 // Two distinct ranges.
911                 t.updatePiecePriorities(l.begin, l.end)
912                 t.updatePiecePriorities(h.begin, h.end)
913         } else {
914                 // Ranges overlap.
915                 end := l.end
916                 if h.end > end {
917                         end = h.end
918                 }
919                 t.updatePiecePriorities(l.begin, end)
920         }
921 }
922
923 func (t *Torrent) maybeNewConns() {
924         // Tickle the accept routine.
925         t.cl.event.Broadcast()
926         t.openNewConns()
927 }
928
929 func (t *Torrent) piecePriorityChanged(piece pieceIndex) {
930         // t.logger.Printf("piece %d priority changed", piece)
931         for c := range t.conns {
932                 if c.updatePiecePriority(piece) {
933                         // log.Print("conn piece priority changed")
934                         c.updateRequests()
935                 }
936         }
937         t.maybeNewConns()
938         t.publishPieceChange(piece)
939 }
940
941 func (t *Torrent) updatePiecePriority(piece pieceIndex) {
942         p := &t.pieces[piece]
943         newPrio := p.uncachedPriority()
944         // t.logger.Printf("torrent %p: piece %d: uncached priority: %v", t, piece, newPrio)
945         if newPrio == PiecePriorityNone {
946                 if !t._pendingPieces.Remove(bitmap.BitIndex(piece)) {
947                         return
948                 }
949         } else {
950                 if !t._pendingPieces.Set(bitmap.BitIndex(piece), newPrio.BitmapPriority()) {
951                         return
952                 }
953         }
954         t.piecePriorityChanged(piece)
955 }
956
957 func (t *Torrent) updateAllPiecePriorities() {
958         t.updatePiecePriorities(0, t.numPieces())
959 }
960
961 // Update all piece priorities in one hit. This function should have the same
962 // output as updatePiecePriority, but across all pieces.
963 func (t *Torrent) updatePiecePriorities(begin, end pieceIndex) {
964         for i := begin; i < end; i++ {
965                 t.updatePiecePriority(i)
966         }
967 }
968
969 // Returns the range of pieces [begin, end) that contains the extent of bytes.
970 func (t *Torrent) byteRegionPieces(off, size int64) (begin, end pieceIndex) {
971         if off >= *t.length {
972                 return
973         }
974         if off < 0 {
975                 size += off
976                 off = 0
977         }
978         if size <= 0 {
979                 return
980         }
981         begin = pieceIndex(off / t.info.PieceLength)
982         end = pieceIndex((off + size + t.info.PieceLength - 1) / t.info.PieceLength)
983         if end > pieceIndex(t.info.NumPieces()) {
984                 end = pieceIndex(t.info.NumPieces())
985         }
986         return
987 }
988
989 // Returns true if all iterations complete without breaking. Returns the read
990 // regions for all readers. The reader regions should not be merged as some
991 // callers depend on this method to enumerate readers.
992 func (t *Torrent) forReaderOffsetPieces(f func(begin, end pieceIndex) (more bool)) (all bool) {
993         for r := range t.readers {
994                 p := r.pieces
995                 if p.begin >= p.end {
996                         continue
997                 }
998                 if !f(p.begin, p.end) {
999                         return false
1000                 }
1001         }
1002         return true
1003 }
1004
1005 func (t *Torrent) piecePriority(piece pieceIndex) piecePriority {
1006         prio, ok := t._pendingPieces.GetPriority(bitmap.BitIndex(piece))
1007         if !ok {
1008                 return PiecePriorityNone
1009         }
1010         if prio > 0 {
1011                 panic(prio)
1012         }
1013         ret := piecePriority(-prio)
1014         if ret == PiecePriorityNone {
1015                 panic(piece)
1016         }
1017         return ret
1018 }
1019
1020 func (t *Torrent) pendRequest(req request) {
1021         ci := chunkIndex(req.chunkSpec, t.chunkSize)
1022         t.pieces[req.Index].pendChunkIndex(ci)
1023 }
1024
1025 func (t *Torrent) pieceCompletionChanged(piece pieceIndex) {
1026         t.tickleReaders()
1027         t.cl.event.Broadcast()
1028         if t.pieceComplete(piece) {
1029                 t.onPieceCompleted(piece)
1030         } else {
1031                 t.onIncompletePiece(piece)
1032         }
1033         t.updatePiecePriority(piece)
1034 }
1035
1036 func (t *Torrent) numReceivedConns() (ret int) {
1037         for c := range t.conns {
1038                 if c.Discovery == PeerSourceIncoming {
1039                         ret++
1040                 }
1041         }
1042         return
1043 }
1044
1045 func (t *Torrent) maxHalfOpen() int {
1046         // Note that if we somehow exceed the maximum established conns, we want
1047         // the negative value to have an effect.
1048         establishedHeadroom := int64(t.maxEstablishedConns - len(t.conns))
1049         extraIncoming := int64(t.numReceivedConns() - t.maxEstablishedConns/2)
1050         // We want to allow some experimentation with new peers, and to try to
1051         // upset an oversupply of received connections.
1052         return int(min(max(5, extraIncoming)+establishedHeadroom, int64(t.cl.config.HalfOpenConnsPerTorrent)))
1053 }
1054
1055 func (t *Torrent) openNewConns() {
1056         defer t.updateWantPeersEvent()
1057         for t.peers.Len() != 0 {
1058                 if !t.wantConns() {
1059                         return
1060                 }
1061                 if len(t.halfOpen) >= t.maxHalfOpen() {
1062                         return
1063                 }
1064                 p := t.peers.PopMax()
1065                 t.initiateConn(p)
1066         }
1067 }
1068
1069 func (t *Torrent) getConnPieceInclination() []int {
1070         _ret := t.connPieceInclinationPool.Get()
1071         if _ret == nil {
1072                 pieceInclinationsNew.Add(1)
1073                 return rand.Perm(int(t.numPieces()))
1074         }
1075         pieceInclinationsReused.Add(1)
1076         return *_ret.(*[]int)
1077 }
1078
1079 func (t *Torrent) putPieceInclination(pi []int) {
1080         t.connPieceInclinationPool.Put(&pi)
1081         pieceInclinationsPut.Add(1)
1082 }
1083
1084 func (t *Torrent) updatePieceCompletion(piece pieceIndex) bool {
1085         p := t.piece(piece)
1086         uncached := t.pieceCompleteUncached(piece)
1087         cached := p.completion()
1088         changed := cached != uncached
1089         complete := uncached.Complete
1090         p.storageCompletionOk = uncached.Ok
1091         t._completedPieces.Set(bitmap.BitIndex(piece), complete)
1092         if complete && len(p.dirtiers) != 0 {
1093                 t.logger.Printf("marked piece %v complete but still has dirtiers", piece)
1094         }
1095         if changed {
1096                 log.Fstr("piece %d completion changed: %+v -> %+v", piece, cached, uncached).WithValues(debugLogValue).Log(t.logger)
1097                 t.pieceCompletionChanged(piece)
1098         }
1099         return changed
1100 }
1101
1102 // Non-blocking read. Client lock is not required.
1103 func (t *Torrent) readAt(b []byte, off int64) (n int, err error) {
1104         p := &t.pieces[off/t.info.PieceLength]
1105         p.waitNoPendingWrites()
1106         return p.Storage().ReadAt(b, off-p.Info().Offset())
1107 }
1108
1109 // Returns an error if the metadata was completed, but couldn't be set for
1110 // some reason. Blame it on the last peer to contribute.
1111 func (t *Torrent) maybeCompleteMetadata() error {
1112         if t.haveInfo() {
1113                 // Nothing to do.
1114                 return nil
1115         }
1116         if !t.haveAllMetadataPieces() {
1117                 // Don't have enough metadata pieces.
1118                 return nil
1119         }
1120         err := t.setInfoBytes(t.metadataBytes)
1121         if err != nil {
1122                 t.invalidateMetadata()
1123                 return fmt.Errorf("error setting info bytes: %s", err)
1124         }
1125         if t.cl.config.Debug {
1126                 t.logger.Printf("%s: got metadata from peers", t)
1127         }
1128         return nil
1129 }
1130
1131 func (t *Torrent) readerPiecePriorities() (now, readahead bitmap.Bitmap) {
1132         t.forReaderOffsetPieces(func(begin, end pieceIndex) bool {
1133                 if end > begin {
1134                         now.Add(bitmap.BitIndex(begin))
1135                         readahead.AddRange(bitmap.BitIndex(begin)+1, bitmap.BitIndex(end))
1136                 }
1137                 return true
1138         })
1139         return
1140 }
1141
1142 func (t *Torrent) needData() bool {
1143         if t.closed.IsSet() {
1144                 return false
1145         }
1146         if !t.haveInfo() {
1147                 return true
1148         }
1149         return t._pendingPieces.Len() != 0
1150 }
1151
1152 func appendMissingStrings(old, new []string) (ret []string) {
1153         ret = old
1154 new:
1155         for _, n := range new {
1156                 for _, o := range old {
1157                         if o == n {
1158                                 continue new
1159                         }
1160                 }
1161                 ret = append(ret, n)
1162         }
1163         return
1164 }
1165
1166 func appendMissingTrackerTiers(existing [][]string, minNumTiers int) (ret [][]string) {
1167         ret = existing
1168         for minNumTiers > len(ret) {
1169                 ret = append(ret, nil)
1170         }
1171         return
1172 }
1173
1174 func (t *Torrent) addTrackers(announceList [][]string) {
1175         fullAnnounceList := &t.metainfo.AnnounceList
1176         t.metainfo.AnnounceList = appendMissingTrackerTiers(*fullAnnounceList, len(announceList))
1177         for tierIndex, trackerURLs := range announceList {
1178                 (*fullAnnounceList)[tierIndex] = appendMissingStrings((*fullAnnounceList)[tierIndex], trackerURLs)
1179         }
1180         t.startMissingTrackerScrapers()
1181         t.updateWantPeersEvent()
1182 }
1183
1184 // Don't call this before the info is available.
1185 func (t *Torrent) bytesCompleted() int64 {
1186         if !t.haveInfo() {
1187                 return 0
1188         }
1189         return t.info.TotalLength() - t.bytesLeft()
1190 }
1191
1192 func (t *Torrent) SetInfoBytes(b []byte) (err error) {
1193         t.cl.lock()
1194         defer t.cl.unlock()
1195         return t.setInfoBytes(b)
1196 }
1197
1198 // Returns true if connection is removed from torrent.Conns.
1199 func (t *Torrent) deleteConnection(c *PeerConn) (ret bool) {
1200         if !c.closed.IsSet() {
1201                 panic("connection is not closed")
1202                 // There are behaviours prevented by the closed state that will fail
1203                 // if the connection has been deleted.
1204         }
1205         _, ret = t.conns[c]
1206         delete(t.conns, c)
1207         torrent.Add("deleted connections", 1)
1208         c.deleteAllRequests()
1209         if len(t.conns) == 0 {
1210                 t.assertNoPendingRequests()
1211         }
1212         return
1213 }
1214
1215 func (t *Torrent) assertNoPendingRequests() {
1216         if len(t.pendingRequests) != 0 {
1217                 panic(t.pendingRequests)
1218         }
1219         //if len(t.lastRequested) != 0 {
1220         //      panic(t.lastRequested)
1221         //}
1222 }
1223
1224 func (t *Torrent) dropConnection(c *PeerConn) {
1225         t.cl.event.Broadcast()
1226         c.close()
1227         if t.deleteConnection(c) {
1228                 t.openNewConns()
1229         }
1230 }
1231
1232 func (t *Torrent) wantPeers() bool {
1233         if t.closed.IsSet() {
1234                 return false
1235         }
1236         if t.peers.Len() > t.cl.config.TorrentPeersLowWater {
1237                 return false
1238         }
1239         return t.needData() || t.seeding()
1240 }
1241
1242 func (t *Torrent) updateWantPeersEvent() {
1243         if t.wantPeers() {
1244                 t.wantPeersEvent.Set()
1245         } else {
1246                 t.wantPeersEvent.Clear()
1247         }
1248 }
1249
1250 // Returns whether the client should make effort to seed the torrent.
1251 func (t *Torrent) seeding() bool {
1252         cl := t.cl
1253         if t.closed.IsSet() {
1254                 return false
1255         }
1256         if cl.config.NoUpload {
1257                 return false
1258         }
1259         if !cl.config.Seed {
1260                 return false
1261         }
1262         if cl.config.DisableAggressiveUpload && t.needData() {
1263                 return false
1264         }
1265         return true
1266 }
1267
1268 func (t *Torrent) startScrapingTracker(_url string) {
1269         if _url == "" {
1270                 return
1271         }
1272         u, err := url.Parse(_url)
1273         if err != nil {
1274                 // URLs with a leading '*' appear to be a uTorrent convention to
1275                 // disable trackers.
1276                 if _url[0] != '*' {
1277                         log.Str("error parsing tracker url").AddValues("url", _url).Log(t.logger)
1278                 }
1279                 return
1280         }
1281         if u.Scheme == "udp" {
1282                 u.Scheme = "udp4"
1283                 t.startScrapingTracker(u.String())
1284                 u.Scheme = "udp6"
1285                 t.startScrapingTracker(u.String())
1286                 return
1287         }
1288         if u.Scheme == "udp4" && (t.cl.config.DisableIPv4Peers || t.cl.config.DisableIPv4) {
1289                 return
1290         }
1291         if u.Scheme == "udp6" && t.cl.config.DisableIPv6 {
1292                 return
1293         }
1294         if _, ok := t.trackerAnnouncers[_url]; ok {
1295                 return
1296         }
1297         newAnnouncer := &trackerScraper{
1298                 u: *u,
1299                 t: t,
1300         }
1301         if t.trackerAnnouncers == nil {
1302                 t.trackerAnnouncers = make(map[string]*trackerScraper)
1303         }
1304         t.trackerAnnouncers[_url] = newAnnouncer
1305         go newAnnouncer.Run()
1306 }
1307
1308 // Adds and starts tracker scrapers for tracker URLs that aren't already
1309 // running.
1310 func (t *Torrent) startMissingTrackerScrapers() {
1311         if t.cl.config.DisableTrackers {
1312                 return
1313         }
1314         t.startScrapingTracker(t.metainfo.Announce)
1315         for _, tier := range t.metainfo.AnnounceList {
1316                 for _, url := range tier {
1317                         t.startScrapingTracker(url)
1318                 }
1319         }
1320 }
1321
1322 // Returns an AnnounceRequest with fields filled out to defaults and current
1323 // values.
1324 func (t *Torrent) announceRequest(event tracker.AnnounceEvent) tracker.AnnounceRequest {
1325         // Note that IPAddress is not set. It's set for UDP inside the tracker
1326         // code, since it's dependent on the network in use.
1327         return tracker.AnnounceRequest{
1328                 Event:    event,
1329                 NumWant:  -1,
1330                 Port:     uint16(t.cl.incomingPeerPort()),
1331                 PeerId:   t.cl.peerID,
1332                 InfoHash: t.infoHash,
1333                 Key:      t.cl.announceKey(),
1334
1335                 // The following are vaguely described in BEP 3.
1336
1337                 Left:     t.bytesLeftAnnounce(),
1338                 Uploaded: t.stats.BytesWrittenData.Int64(),
1339                 // There's no mention of wasted or unwanted download in the BEP.
1340                 Downloaded: t.stats.BytesReadUsefulData.Int64(),
1341         }
1342 }
1343
1344 // Adds peers revealed in an announce until the announce ends, or we have
1345 // enough peers.
1346 func (t *Torrent) consumeDhtAnnouncePeers(pvs <-chan dht.PeersValues) {
1347         cl := t.cl
1348         for v := range pvs {
1349                 cl.lock()
1350                 for _, cp := range v.Peers {
1351                         if cp.Port == 0 {
1352                                 // Can't do anything with this.
1353                                 continue
1354                         }
1355                         t.addPeer(Peer{
1356                                 Addr:   ipPortAddr{cp.IP, cp.Port},
1357                                 Source: PeerSourceDhtGetPeers,
1358                         })
1359                 }
1360                 cl.unlock()
1361         }
1362 }
1363
1364 func (t *Torrent) announceToDht(impliedPort bool, s DhtServer) error {
1365         ps, err := s.Announce(t.infoHash, t.cl.incomingPeerPort(), impliedPort)
1366         if err != nil {
1367                 return err
1368         }
1369         go t.consumeDhtAnnouncePeers(ps.Peers())
1370         select {
1371         case <-t.closed.LockedChan(t.cl.locker()):
1372         case <-time.After(5 * time.Minute):
1373         }
1374         ps.Close()
1375         return nil
1376 }
1377
1378 func (t *Torrent) dhtAnnouncer(s DhtServer) {
1379         cl := t.cl
1380         for {
1381                 select {
1382                 case <-t.closed.LockedChan(cl.locker()):
1383                         return
1384                 case <-t.wantPeersEvent.LockedChan(cl.locker()):
1385                 }
1386                 cl.lock()
1387                 t.numDHTAnnounces++
1388                 cl.unlock()
1389                 err := t.announceToDht(true, s)
1390                 if err != nil {
1391                         t.logger.Printf("error announcing %q to DHT: %s", t, err)
1392                 }
1393         }
1394 }
1395
1396 func (t *Torrent) addPeers(peers []Peer) {
1397         for _, p := range peers {
1398                 t.addPeer(p)
1399         }
1400 }
1401
1402 func (t *Torrent) Stats() TorrentStats {
1403         t.cl.rLock()
1404         defer t.cl.rUnlock()
1405         return t.statsLocked()
1406 }
1407
1408 func (t *Torrent) statsLocked() (ret TorrentStats) {
1409         ret.ActivePeers = len(t.conns)
1410         ret.HalfOpenPeers = len(t.halfOpen)
1411         ret.PendingPeers = t.peers.Len()
1412         ret.TotalPeers = t.numTotalPeers()
1413         ret.ConnectedSeeders = 0
1414         for c := range t.conns {
1415                 if all, ok := c.peerHasAllPieces(); all && ok {
1416                         ret.ConnectedSeeders++
1417                 }
1418         }
1419         ret.ConnStats = t.stats.Copy()
1420         return
1421 }
1422
1423 // The total number of peers in the torrent.
1424 func (t *Torrent) numTotalPeers() int {
1425         peers := make(map[string]struct{})
1426         for conn := range t.conns {
1427                 ra := conn.conn.RemoteAddr()
1428                 if ra == nil {
1429                         // It's been closed and doesn't support RemoteAddr.
1430                         continue
1431                 }
1432                 peers[ra.String()] = struct{}{}
1433         }
1434         for addr := range t.halfOpen {
1435                 peers[addr] = struct{}{}
1436         }
1437         t.peers.Each(func(peer Peer) {
1438                 peers[peer.Addr.String()] = struct{}{}
1439         })
1440         return len(peers)
1441 }
1442
1443 // Reconcile bytes transferred before connection was associated with a
1444 // torrent.
1445 func (t *Torrent) reconcileHandshakeStats(c *PeerConn) {
1446         if c._stats != (ConnStats{
1447                 // Handshakes should only increment these fields:
1448                 BytesWritten: c._stats.BytesWritten,
1449                 BytesRead:    c._stats.BytesRead,
1450         }) {
1451                 panic("bad stats")
1452         }
1453         c.postHandshakeStats(func(cs *ConnStats) {
1454                 cs.BytesRead.Add(c._stats.BytesRead.Int64())
1455                 cs.BytesWritten.Add(c._stats.BytesWritten.Int64())
1456         })
1457         c.reconciledHandshakeStats = true
1458 }
1459
1460 // Returns true if the connection is added.
1461 func (t *Torrent) addConnection(c *PeerConn) (err error) {
1462         defer func() {
1463                 if err == nil {
1464                         torrent.Add("added connections", 1)
1465                 }
1466         }()
1467         if t.closed.IsSet() {
1468                 return errors.New("torrent closed")
1469         }
1470         for c0 := range t.conns {
1471                 if c.PeerID != c0.PeerID {
1472                         continue
1473                 }
1474                 if !t.cl.config.dropDuplicatePeerIds {
1475                         continue
1476                 }
1477                 if left, ok := c.hasPreferredNetworkOver(c0); ok && left {
1478                         c0.close()
1479                         t.deleteConnection(c0)
1480                 } else {
1481                         return errors.New("existing connection preferred")
1482                 }
1483         }
1484         if len(t.conns) >= t.maxEstablishedConns {
1485                 c := t.worstBadConn()
1486                 if c == nil {
1487                         return errors.New("don't want conns")
1488                 }
1489                 c.close()
1490                 t.deleteConnection(c)
1491         }
1492         if len(t.conns) >= t.maxEstablishedConns {
1493                 panic(len(t.conns))
1494         }
1495         t.conns[c] = struct{}{}
1496         return nil
1497 }
1498
1499 func (t *Torrent) wantConns() bool {
1500         if !t.networkingEnabled {
1501                 return false
1502         }
1503         if t.closed.IsSet() {
1504                 return false
1505         }
1506         if !t.seeding() && !t.needData() {
1507                 return false
1508         }
1509         if len(t.conns) < t.maxEstablishedConns {
1510                 return true
1511         }
1512         return t.worstBadConn() != nil
1513 }
1514
1515 func (t *Torrent) SetMaxEstablishedConns(max int) (oldMax int) {
1516         t.cl.lock()
1517         defer t.cl.unlock()
1518         oldMax = t.maxEstablishedConns
1519         t.maxEstablishedConns = max
1520         wcs := slices.HeapInterface(slices.FromMapKeys(t.conns), worseConn)
1521         for len(t.conns) > t.maxEstablishedConns && wcs.Len() > 0 {
1522                 t.dropConnection(wcs.Pop().(*PeerConn))
1523         }
1524         t.openNewConns()
1525         return oldMax
1526 }
1527
1528 func (t *Torrent) pieceHashed(piece pieceIndex, passed bool, hashIoErr error) {
1529         t.logger.Log(log.Fstr("hashed piece %d (passed=%t)", piece, passed).WithValues(debugLogValue))
1530         p := t.piece(piece)
1531         p.numVerifies++
1532         t.cl.event.Broadcast()
1533         if t.closed.IsSet() {
1534                 return
1535         }
1536
1537         // Don't score the first time a piece is hashed, it could be an initial check.
1538         if p.storageCompletionOk {
1539                 if passed {
1540                         pieceHashedCorrect.Add(1)
1541                 } else {
1542                         log.Fmsg("piece %d failed hash: %d connections contributed", piece, len(p.dirtiers)).AddValues(t, p).Log(t.logger)
1543                         pieceHashedNotCorrect.Add(1)
1544                 }
1545         }
1546
1547         if passed {
1548                 if len(p.dirtiers) != 0 {
1549                         // Don't increment stats above connection-level for every involved connection.
1550                         t.allStats((*ConnStats).incrementPiecesDirtiedGood)
1551                 }
1552                 for c := range p.dirtiers {
1553                         c._stats.incrementPiecesDirtiedGood()
1554                 }
1555                 t.clearPieceTouchers(piece)
1556                 err := p.Storage().MarkComplete()
1557                 if err != nil {
1558                         t.logger.Printf("%T: error marking piece complete %d: %s", t.storage, piece, err)
1559                 }
1560                 t.pendAllChunkSpecs(piece)
1561         } else {
1562                 if len(p.dirtiers) != 0 && p.allChunksDirty() && hashIoErr == nil {
1563                         // Peers contributed to all the data for this piece hash failure, and the failure was
1564                         // not due to errors in the storage (such as data being dropped in a cache).
1565
1566                         // Increment Torrent and above stats, and then specific connections.
1567                         t.allStats((*ConnStats).incrementPiecesDirtiedBad)
1568                         for c := range p.dirtiers {
1569                                 // Y u do dis peer?!
1570                                 c.stats().incrementPiecesDirtiedBad()
1571                         }
1572
1573                         bannableTouchers := make([]*PeerConn, 0, len(p.dirtiers))
1574                         for c := range p.dirtiers {
1575                                 if !c.trusted {
1576                                         bannableTouchers = append(bannableTouchers, c)
1577                                 }
1578                         }
1579                         t.clearPieceTouchers(piece)
1580                         slices.Sort(bannableTouchers, connLessTrusted)
1581
1582                         if t.cl.config.Debug {
1583                                 t.logger.Printf(
1584                                         "bannable conns by trust for piece %d: %v",
1585                                         piece,
1586                                         func() (ret []connectionTrust) {
1587                                                 for _, c := range bannableTouchers {
1588                                                         ret = append(ret, c.trust())
1589                                                 }
1590                                                 return
1591                                         }(),
1592                                 )
1593                         }
1594
1595                         if len(bannableTouchers) >= 1 {
1596                                 c := bannableTouchers[0]
1597                                 t.cl.banPeerIP(c.remoteIp())
1598                                 c.drop()
1599                         }
1600                 }
1601                 t.onIncompletePiece(piece)
1602                 p.Storage().MarkNotComplete()
1603         }
1604         t.updatePieceCompletion(piece)
1605 }
1606
1607 func (t *Torrent) cancelRequestsForPiece(piece pieceIndex) {
1608         // TODO: Make faster
1609         for cn := range t.conns {
1610                 cn.tickleWriter()
1611         }
1612 }
1613
1614 func (t *Torrent) onPieceCompleted(piece pieceIndex) {
1615         t.pendAllChunkSpecs(piece)
1616         t.cancelRequestsForPiece(piece)
1617         for conn := range t.conns {
1618                 conn.have(piece)
1619         }
1620 }
1621
1622 // Called when a piece is found to be not complete.
1623 func (t *Torrent) onIncompletePiece(piece pieceIndex) {
1624         if t.pieceAllDirty(piece) {
1625                 t.pendAllChunkSpecs(piece)
1626         }
1627         if !t.wantPieceIndex(piece) {
1628                 // t.logger.Printf("piece %d incomplete and unwanted", piece)
1629                 return
1630         }
1631         // We could drop any connections that we told we have a piece that we
1632         // don't here. But there's a test failure, and it seems clients don't care
1633         // if you request pieces that you already claim to have. Pruning bad
1634         // connections might just remove any connections that aren't treating us
1635         // favourably anyway.
1636
1637         // for c := range t.conns {
1638         //      if c.sentHave(piece) {
1639         //              c.drop()
1640         //      }
1641         // }
1642         for conn := range t.conns {
1643                 if conn.peerHasPiece(piece) {
1644                         conn.updateRequests()
1645                 }
1646         }
1647 }
1648
1649 func (t *Torrent) tryCreateMorePieceHashers() {
1650         for !t.closed.IsSet() && t.activePieceHashes < 2 && t.tryCreatePieceHasher() {
1651         }
1652 }
1653
1654 func (t *Torrent) tryCreatePieceHasher() bool {
1655         if t.storage == nil {
1656                 return false
1657         }
1658         pi, ok := t.getPieceToHash()
1659         if !ok {
1660                 return false
1661         }
1662         p := t.piece(pi)
1663         t.piecesQueuedForHash.Remove(pi)
1664         p.hashing = true
1665         t.publishPieceChange(pi)
1666         t.updatePiecePriority(pi)
1667         t.storageLock.RLock()
1668         t.activePieceHashes++
1669         go t.pieceHasher(pi)
1670         return true
1671 }
1672
1673 func (t *Torrent) getPieceToHash() (ret pieceIndex, ok bool) {
1674         t.piecesQueuedForHash.IterTyped(func(i pieceIndex) bool {
1675                 if t.piece(i).hashing {
1676                         return true
1677                 }
1678                 ret = i
1679                 ok = true
1680                 return false
1681         })
1682         return
1683 }
1684
1685 func (t *Torrent) pieceHasher(index pieceIndex) {
1686         p := t.piece(index)
1687         sum, copyErr := t.hashPiece(index)
1688         correct := sum == *p.hash
1689         if !correct {
1690                 log.Fmsg("piece %v (%s) hash failure copy error: %v", p, p.hash.HexString(), copyErr).Log(t.logger)
1691         }
1692         t.storageLock.RUnlock()
1693         t.cl.lock()
1694         defer t.cl.unlock()
1695         p.hashing = false
1696         t.updatePiecePriority(index)
1697         t.pieceHashed(index, correct, copyErr)
1698         t.publishPieceChange(index)
1699         t.activePieceHashes--
1700         t.tryCreateMorePieceHashers()
1701 }
1702
1703 // Return the connections that touched a piece, and clear the entries while doing it.
1704 func (t *Torrent) clearPieceTouchers(pi pieceIndex) {
1705         p := t.piece(pi)
1706         for c := range p.dirtiers {
1707                 delete(c.peerTouchedPieces, pi)
1708                 delete(p.dirtiers, c)
1709         }
1710 }
1711
1712 func (t *Torrent) connsAsSlice() (ret []*PeerConn) {
1713         for c := range t.conns {
1714                 ret = append(ret, c)
1715         }
1716         return
1717 }
1718
1719 func (t *Torrent) queuePieceCheck(pieceIndex pieceIndex) {
1720         piece := t.piece(pieceIndex)
1721         if piece.queuedForHash() {
1722                 return
1723         }
1724         t.piecesQueuedForHash.Add(bitmap.BitIndex(pieceIndex))
1725         t.publishPieceChange(pieceIndex)
1726         t.updatePiecePriority(pieceIndex)
1727         t.tryCreateMorePieceHashers()
1728 }
1729
1730 // Forces all the pieces to be re-hashed. See also Piece.VerifyData. This should not be called
1731 // before the Info is available.
1732 func (t *Torrent) VerifyData() {
1733         for i := pieceIndex(0); i < t.NumPieces(); i++ {
1734                 t.Piece(i).VerifyData()
1735         }
1736 }
1737
1738 // Start the process of connecting to the given peer for the given torrent if appropriate.
1739 func (t *Torrent) initiateConn(peer Peer) {
1740         if peer.Id == t.cl.peerID {
1741                 return
1742         }
1743
1744         if t.cl.badPeerAddr(peer.Addr) && !peer.Trusted {
1745                 return
1746         }
1747         addr := peer.Addr
1748         if t.addrActive(addr.String()) {
1749                 return
1750         }
1751         t.halfOpen[addr.String()] = peer
1752         go t.cl.outgoingConnection(t, addr, peer.Source, peer.Trusted)
1753 }
1754
1755 // Adds a trusted, pending peer for each of the given Client's addresses. Typically used in tests to
1756 // quickly make one Client visible to the Torrent of another Client.
1757 func (t *Torrent) AddClientPeer(cl *Client) {
1758         t.AddPeers(func() (ps []Peer) {
1759                 for _, la := range cl.ListenAddrs() {
1760                         ps = append(ps, Peer{
1761                                 Addr:    la,
1762                                 Trusted: true,
1763                         })
1764                 }
1765                 return
1766         }())
1767 }
1768
1769 // All stats that include this Torrent. Useful when we want to increment ConnStats but not for every
1770 // connection.
1771 func (t *Torrent) allStats(f func(*ConnStats)) {
1772         f(&t.stats)
1773         f(&t.cl.stats)
1774 }
1775
1776 func (t *Torrent) hashingPiece(i pieceIndex) bool {
1777         return t.pieces[i].hashing
1778 }
1779
1780 func (t *Torrent) pieceQueuedForHash(i pieceIndex) bool {
1781         return t.piecesQueuedForHash.Get(bitmap.BitIndex(i))
1782 }
1783
1784 func (t *Torrent) dialTimeout() time.Duration {
1785         return reducedDialTimeout(t.cl.config.MinDialTimeout, t.cl.config.NominalDialTimeout, t.cl.config.HalfOpenConnsPerTorrent, t.peers.Len())
1786 }
1787
1788 func (t *Torrent) piece(i int) *Piece {
1789         return &t.pieces[i]
1790 }
1791
1792 func (t *Torrent) requestStrategyTorrent() requestStrategyTorrent {
1793         return t
1794 }
1795
1796 type torrentRequestStrategyCallbacks struct {
1797         t *Torrent
1798 }
1799
1800 func (cb torrentRequestStrategyCallbacks) requestTimedOut(r request) {
1801         torrent.Add("request timeouts", 1)
1802         cb.t.cl.lock()
1803         defer cb.t.cl.unlock()
1804         for cn := range cb.t.conns {
1805                 if cn.peerHasPiece(pieceIndex(r.Index)) {
1806                         cn.updateRequests()
1807                 }
1808         }
1809
1810 }
1811
1812 func (t *Torrent) requestStrategyCallbacks() requestStrategyCallbacks {
1813         return torrentRequestStrategyCallbacks{t}
1814 }
1815
1816 func (t *Torrent) onWriteChunkErr(err error) {
1817         if t.userOnWriteChunkErr != nil {
1818                 go t.userOnWriteChunkErr(err)
1819                 return
1820         }
1821         t.disallowDataDownloadLocked()
1822 }
1823
1824 func (t *Torrent) DisallowDataDownload() {
1825         t.cl.lock()
1826         defer t.cl.unlock()
1827         t.disallowDataDownloadLocked()
1828 }
1829
1830 func (t *Torrent) disallowDataDownloadLocked() {
1831         log.Printf("disallowing data download")
1832         t.dataDownloadDisallowed = true
1833         for c := range t.conns {
1834                 c.updateRequests()
1835         }
1836 }
1837
1838 func (t *Torrent) AllowDataDownload() {
1839         t.cl.lock()
1840         defer t.cl.unlock()
1841         log.Printf("AllowDataDownload")
1842         t.dataDownloadDisallowed = false
1843         for c := range t.conns {
1844                 c.updateRequests()
1845         }
1846
1847 }
1848
1849 func (t *Torrent) SetOnWriteChunkError(f func(error)) {
1850         t.cl.lock()
1851         defer t.cl.unlock()
1852         t.userOnWriteChunkErr = f
1853 }