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