]> Sergey Matveev's repositories - btrtrc.git/blob - torrent.go
fixup! [webseed] Add a custom URL encoder for webseeds
[btrtrc.git] / torrent.go
1 package torrent
2
3 import (
4         "bytes"
5         "container/heap"
6         "context"
7         "crypto/sha1"
8         "errors"
9         "fmt"
10         "io"
11         "net/netip"
12         "net/url"
13         "sort"
14         "strings"
15         "text/tabwriter"
16         "time"
17         "unsafe"
18
19         "github.com/RoaringBitmap/roaring"
20         "github.com/anacrolix/chansync"
21         "github.com/anacrolix/chansync/events"
22         "github.com/anacrolix/dht/v2"
23         . "github.com/anacrolix/generics"
24         "github.com/anacrolix/log"
25         "github.com/anacrolix/missinggo/perf"
26         "github.com/anacrolix/missinggo/slices"
27         "github.com/anacrolix/missinggo/v2"
28         "github.com/anacrolix/missinggo/v2/bitmap"
29         "github.com/anacrolix/missinggo/v2/pubsub"
30         "github.com/anacrolix/multiless"
31         "github.com/anacrolix/sync"
32         request_strategy "github.com/anacrolix/torrent/request-strategy"
33         "github.com/davecgh/go-spew/spew"
34         "github.com/pion/datachannel"
35
36         "github.com/anacrolix/torrent/bencode"
37         "github.com/anacrolix/torrent/common"
38         "github.com/anacrolix/torrent/metainfo"
39         pp "github.com/anacrolix/torrent/peer_protocol"
40         "github.com/anacrolix/torrent/segments"
41         "github.com/anacrolix/torrent/storage"
42         "github.com/anacrolix/torrent/tracker"
43         "github.com/anacrolix/torrent/webseed"
44         "github.com/anacrolix/torrent/webtorrent"
45 )
46
47 // Maintains state of torrent within a Client. Many methods should not be called before the info is
48 // available, see .Info and .GotInfo.
49 type Torrent struct {
50         // Torrent-level aggregate statistics. First in struct to ensure 64-bit
51         // alignment. See #262.
52         stats  ConnStats
53         cl     *Client
54         logger log.Logger
55
56         networkingEnabled      chansync.Flag
57         dataDownloadDisallowed chansync.Flag
58         dataUploadDisallowed   bool
59         userOnWriteChunkErr    func(error)
60
61         closed   chansync.SetOnce
62         infoHash metainfo.Hash
63         pieces   []Piece
64         // Values are the piece indices that changed.
65         pieceStateChanges pubsub.PubSub[PieceStateChange]
66         // The size of chunks to request from peers over the wire. This is
67         // normally 16KiB by convention these days.
68         chunkSize pp.Integer
69         chunkPool sync.Pool
70         // Total length of the torrent in bytes. Stored because it's not O(1) to
71         // get this from the info dict.
72         length *int64
73
74         // The storage to open when the info dict becomes available.
75         storageOpener *storage.Client
76         // Storage for torrent data.
77         storage *storage.Torrent
78         // Read-locked for using storage, and write-locked for Closing.
79         storageLock sync.RWMutex
80
81         // TODO: Only announce stuff is used?
82         metainfo metainfo.MetaInfo
83
84         // The info dict. nil if we don't have it (yet).
85         info      *metainfo.Info
86         fileIndex segments.Index
87         files     *[]*File
88
89         webSeeds map[string]*Peer
90         // Active peer connections, running message stream loops. TODO: Make this
91         // open (not-closed) connections only.
92         conns               map[*PeerConn]struct{}
93         maxEstablishedConns int
94         // Set of addrs to which we're attempting to connect. Connections are
95         // half-open until all handshakes are completed.
96         halfOpen map[string]PeerInfo
97
98         // Reserve of peers to connect to. A peer can be both here and in the
99         // active connections if were told about the peer after connecting with
100         // them. That encourages us to reconnect to peers that are well known in
101         // the swarm.
102         peers prioritizedPeers
103         // Whether we want to know to know more peers.
104         wantPeersEvent missinggo.Event
105         // An announcer for each tracker URL.
106         trackerAnnouncers map[string]torrentTrackerAnnouncer
107         // How many times we've initiated a DHT announce. TODO: Move into stats.
108         numDHTAnnounces int
109
110         // Name used if the info name isn't available. Should be cleared when the
111         // Info does become available.
112         nameMu      sync.RWMutex
113         displayName string
114
115         // The bencoded bytes of the info dict. This is actively manipulated if
116         // the info bytes aren't initially available, and we try to fetch them
117         // from peers.
118         metadataBytes []byte
119         // Each element corresponds to the 16KiB metadata pieces. If true, we have
120         // received that piece.
121         metadataCompletedChunks []bool
122         metadataChanged         sync.Cond
123
124         // Closed when .Info is obtained.
125         gotMetainfoC chan struct{}
126
127         readers                map[*reader]struct{}
128         _readerNowPieces       bitmap.Bitmap
129         _readerReadaheadPieces bitmap.Bitmap
130
131         // A cache of pieces we need to get. Calculated from various piece and
132         // file priorities and completion states elsewhere.
133         _pendingPieces roaring.Bitmap
134         // A cache of completed piece indices.
135         _completedPieces roaring.Bitmap
136         // Pieces that need to be hashed.
137         piecesQueuedForHash       bitmap.Bitmap
138         activePieceHashes         int
139         initialPieceCheckDisabled bool
140
141         connsWithAllPieces map[*Peer]struct{}
142         // Count of each request across active connections.
143         pendingRequests map[RequestIndex]*Peer
144         lastRequested   map[RequestIndex]time.Time
145         // Chunks we've written to since the corresponding piece was last checked.
146         dirtyChunks roaring.Bitmap
147
148         pex pexState
149
150         // Is On when all pieces are complete.
151         Complete chansync.Flag
152
153         // Torrent sources in use keyed by the source string.
154         activeSources sync.Map
155         sourcesLogger log.Logger
156
157         smartBanCache smartBanCache
158 }
159
160 func (t *Torrent) selectivePieceAvailabilityFromPeers(i pieceIndex) (count int) {
161         // This could be done with roaring.BitSliceIndexing.
162         t.iterPeers(func(peer *Peer) {
163                 if _, ok := t.connsWithAllPieces[peer]; ok {
164                         return
165                 }
166                 if peer.peerHasPiece(i) {
167                         count++
168                 }
169         })
170         return
171 }
172
173 func (t *Torrent) decPieceAvailability(i pieceIndex) {
174         if !t.haveInfo() {
175                 return
176         }
177         p := t.piece(i)
178         if p.relativeAvailability <= 0 {
179                 panic(p.relativeAvailability)
180         }
181         p.relativeAvailability--
182         t.updatePieceRequestOrder(i)
183 }
184
185 func (t *Torrent) incPieceAvailability(i pieceIndex) {
186         // If we don't the info, this should be reconciled when we do.
187         if t.haveInfo() {
188                 p := t.piece(i)
189                 p.relativeAvailability++
190                 t.updatePieceRequestOrder(i)
191         }
192 }
193
194 func (t *Torrent) readerNowPieces() bitmap.Bitmap {
195         return t._readerNowPieces
196 }
197
198 func (t *Torrent) readerReadaheadPieces() bitmap.Bitmap {
199         return t._readerReadaheadPieces
200 }
201
202 func (t *Torrent) ignorePieceForRequests(i pieceIndex) bool {
203         return !t.wantPieceIndex(i)
204 }
205
206 // Returns a channel that is closed when the Torrent is closed.
207 func (t *Torrent) Closed() events.Done {
208         return t.closed.Done()
209 }
210
211 // KnownSwarm returns the known subset of the peers in the Torrent's swarm, including active,
212 // pending, and half-open peers.
213 func (t *Torrent) KnownSwarm() (ks []PeerInfo) {
214         // Add pending peers to the list
215         t.peers.Each(func(peer PeerInfo) {
216                 ks = append(ks, peer)
217         })
218
219         // Add half-open peers to the list
220         for _, peer := range t.halfOpen {
221                 ks = append(ks, peer)
222         }
223
224         // Add active peers to the list
225         for conn := range t.conns {
226                 ks = append(ks, PeerInfo{
227                         Id:     conn.PeerID,
228                         Addr:   conn.RemoteAddr,
229                         Source: conn.Discovery,
230                         // > If the connection is encrypted, that's certainly enough to set SupportsEncryption.
231                         // > But if we're not connected to them with an encrypted connection, I couldn't say
232                         // > what's appropriate. We can carry forward the SupportsEncryption value as we
233                         // > received it from trackers/DHT/PEX, or just use the encryption state for the
234                         // > connection. It's probably easiest to do the latter for now.
235                         // https://github.com/anacrolix/torrent/pull/188
236                         SupportsEncryption: conn.headerEncrypted,
237                 })
238         }
239
240         return
241 }
242
243 func (t *Torrent) setChunkSize(size pp.Integer) {
244         t.chunkSize = size
245         t.chunkPool = sync.Pool{
246                 New: func() interface{} {
247                         b := make([]byte, size)
248                         return &b
249                 },
250         }
251 }
252
253 func (t *Torrent) pieceComplete(piece pieceIndex) bool {
254         return t._completedPieces.Contains(bitmap.BitIndex(piece))
255 }
256
257 func (t *Torrent) pieceCompleteUncached(piece pieceIndex) storage.Completion {
258         if t.storage == nil {
259                 return storage.Completion{Complete: false, Ok: true}
260         }
261         return t.pieces[piece].Storage().Completion()
262 }
263
264 // There's a connection to that address already.
265 func (t *Torrent) addrActive(addr string) bool {
266         if _, ok := t.halfOpen[addr]; ok {
267                 return true
268         }
269         for c := range t.conns {
270                 ra := c.RemoteAddr
271                 if ra.String() == addr {
272                         return true
273                 }
274         }
275         return false
276 }
277
278 func (t *Torrent) appendUnclosedConns(ret []*PeerConn) []*PeerConn {
279         return t.appendConns(ret, func(conn *PeerConn) bool {
280                 return !conn.closed.IsSet()
281         })
282 }
283
284 func (t *Torrent) appendConns(ret []*PeerConn, f func(*PeerConn) bool) []*PeerConn {
285         for c := range t.conns {
286                 if f(c) {
287                         ret = append(ret, c)
288                 }
289         }
290         return ret
291 }
292
293 func (t *Torrent) addPeer(p PeerInfo) (added bool) {
294         cl := t.cl
295         torrent.Add(fmt.Sprintf("peers added by source %q", p.Source), 1)
296         if t.closed.IsSet() {
297                 return false
298         }
299         if ipAddr, ok := tryIpPortFromNetAddr(p.Addr); ok {
300                 if cl.badPeerIPPort(ipAddr.IP, ipAddr.Port) {
301                         torrent.Add("peers not added because of bad addr", 1)
302                         // cl.logger.Printf("peers not added because of bad addr: %v", p)
303                         return false
304                 }
305         }
306         if replaced, ok := t.peers.AddReturningReplacedPeer(p); ok {
307                 torrent.Add("peers replaced", 1)
308                 if !replaced.equal(p) {
309                         t.logger.WithDefaultLevel(log.Debug).Printf("added %v replacing %v", p, replaced)
310                         added = true
311                 }
312         } else {
313                 added = true
314         }
315         t.openNewConns()
316         for t.peers.Len() > cl.config.TorrentPeersHighWater {
317                 _, ok := t.peers.DeleteMin()
318                 if ok {
319                         torrent.Add("excess reserve peers discarded", 1)
320                 }
321         }
322         return
323 }
324
325 func (t *Torrent) invalidateMetadata() {
326         for i := 0; i < len(t.metadataCompletedChunks); i++ {
327                 t.metadataCompletedChunks[i] = false
328         }
329         t.nameMu.Lock()
330         t.gotMetainfoC = make(chan struct{})
331         t.info = nil
332         t.nameMu.Unlock()
333 }
334
335 func (t *Torrent) saveMetadataPiece(index int, data []byte) {
336         if t.haveInfo() {
337                 return
338         }
339         if index >= len(t.metadataCompletedChunks) {
340                 t.logger.Printf("%s: ignoring metadata piece %d", t, index)
341                 return
342         }
343         copy(t.metadataBytes[(1<<14)*index:], data)
344         t.metadataCompletedChunks[index] = true
345 }
346
347 func (t *Torrent) metadataPieceCount() int {
348         return (len(t.metadataBytes) + (1 << 14) - 1) / (1 << 14)
349 }
350
351 func (t *Torrent) haveMetadataPiece(piece int) bool {
352         if t.haveInfo() {
353                 return (1<<14)*piece < len(t.metadataBytes)
354         } else {
355                 return piece < len(t.metadataCompletedChunks) && t.metadataCompletedChunks[piece]
356         }
357 }
358
359 func (t *Torrent) metadataSize() int {
360         return len(t.metadataBytes)
361 }
362
363 func infoPieceHashes(info *metainfo.Info) (ret [][]byte) {
364         for i := 0; i < len(info.Pieces); i += sha1.Size {
365                 ret = append(ret, info.Pieces[i:i+sha1.Size])
366         }
367         return
368 }
369
370 func (t *Torrent) makePieces() {
371         hashes := infoPieceHashes(t.info)
372         t.pieces = make([]Piece, len(hashes))
373         for i, hash := range hashes {
374                 piece := &t.pieces[i]
375                 piece.t = t
376                 piece.index = pieceIndex(i)
377                 piece.noPendingWrites.L = &piece.pendingWritesMutex
378                 piece.hash = (*metainfo.Hash)(unsafe.Pointer(&hash[0]))
379                 files := *t.files
380                 beginFile := pieceFirstFileIndex(piece.torrentBeginOffset(), files)
381                 endFile := pieceEndFileIndex(piece.torrentEndOffset(), files)
382                 piece.files = files[beginFile:endFile]
383                 piece.undirtiedChunksIter = undirtiedChunksIter{
384                         TorrentDirtyChunks: &t.dirtyChunks,
385                         StartRequestIndex:  piece.requestIndexOffset(),
386                         EndRequestIndex:    piece.requestIndexOffset() + piece.numChunks(),
387                 }
388         }
389 }
390
391 // Returns the index of the first file containing the piece. files must be
392 // ordered by offset.
393 func pieceFirstFileIndex(pieceOffset int64, files []*File) int {
394         for i, f := range files {
395                 if f.offset+f.length > pieceOffset {
396                         return i
397                 }
398         }
399         return 0
400 }
401
402 // Returns the index after the last file containing the piece. files must be
403 // ordered by offset.
404 func pieceEndFileIndex(pieceEndOffset int64, files []*File) int {
405         for i, f := range files {
406                 if f.offset+f.length >= pieceEndOffset {
407                         return i + 1
408                 }
409         }
410         return 0
411 }
412
413 func (t *Torrent) cacheLength() {
414         var l int64
415         for _, f := range t.info.UpvertedFiles() {
416                 l += f.Length
417         }
418         t.length = &l
419 }
420
421 // TODO: This shouldn't fail for storage reasons. Instead we should handle storage failure
422 // separately.
423 func (t *Torrent) setInfo(info *metainfo.Info) error {
424         if err := validateInfo(info); err != nil {
425                 return fmt.Errorf("bad info: %s", err)
426         }
427         if t.storageOpener != nil {
428                 var err error
429                 t.storage, err = t.storageOpener.OpenTorrent(info, t.infoHash)
430                 if err != nil {
431                         return fmt.Errorf("error opening torrent storage: %s", err)
432                 }
433         }
434         t.nameMu.Lock()
435         t.info = info
436         t.nameMu.Unlock()
437         t.updateComplete()
438         t.fileIndex = segments.NewIndex(common.LengthIterFromUpvertedFiles(info.UpvertedFiles()))
439         t.displayName = "" // Save a few bytes lol.
440         t.initFiles()
441         t.cacheLength()
442         t.makePieces()
443         return nil
444 }
445
446 func (t *Torrent) pieceRequestOrderKey(i int) request_strategy.PieceRequestOrderKey {
447         return request_strategy.PieceRequestOrderKey{
448                 InfoHash: t.infoHash,
449                 Index:    i,
450         }
451 }
452
453 // This seems to be all the follow-up tasks after info is set, that can't fail.
454 func (t *Torrent) onSetInfo() {
455         t.initPieceRequestOrder()
456         for i := range t.pieces {
457                 p := &t.pieces[i]
458                 // Need to add relativeAvailability before updating piece completion, as that may result in conns
459                 // being dropped.
460                 if p.relativeAvailability != 0 {
461                         panic(p.relativeAvailability)
462                 }
463                 p.relativeAvailability = t.selectivePieceAvailabilityFromPeers(i)
464                 t.addRequestOrderPiece(i)
465                 t.updatePieceCompletion(pieceIndex(i))
466                 if !t.initialPieceCheckDisabled && !p.storageCompletionOk {
467                         // t.logger.Printf("piece %s completion unknown, queueing check", p)
468                         t.queuePieceCheck(pieceIndex(i))
469                 }
470         }
471         t.cl.event.Broadcast()
472         close(t.gotMetainfoC)
473         t.updateWantPeersEvent()
474         t.pendingRequests = make(map[RequestIndex]*Peer)
475         t.lastRequested = make(map[RequestIndex]time.Time)
476         t.tryCreateMorePieceHashers()
477         t.iterPeers(func(p *Peer) {
478                 p.onGotInfo(t.info)
479                 p.updateRequests("onSetInfo")
480         })
481 }
482
483 // Called when metadata for a torrent becomes available.
484 func (t *Torrent) setInfoBytesLocked(b []byte) error {
485         if metainfo.HashBytes(b) != t.infoHash {
486                 return errors.New("info bytes have wrong hash")
487         }
488         var info metainfo.Info
489         if err := bencode.Unmarshal(b, &info); err != nil {
490                 return fmt.Errorf("error unmarshalling info bytes: %s", err)
491         }
492         t.metadataBytes = b
493         t.metadataCompletedChunks = nil
494         if t.info != nil {
495                 return nil
496         }
497         if err := t.setInfo(&info); err != nil {
498                 return err
499         }
500         t.onSetInfo()
501         return nil
502 }
503
504 func (t *Torrent) haveAllMetadataPieces() bool {
505         if t.haveInfo() {
506                 return true
507         }
508         if t.metadataCompletedChunks == nil {
509                 return false
510         }
511         for _, have := range t.metadataCompletedChunks {
512                 if !have {
513                         return false
514                 }
515         }
516         return true
517 }
518
519 // TODO: Propagate errors to disconnect peer.
520 func (t *Torrent) setMetadataSize(size int) (err error) {
521         if t.haveInfo() {
522                 // We already know the correct metadata size.
523                 return
524         }
525         if uint32(size) > maxMetadataSize {
526                 return errors.New("bad size")
527         }
528         if len(t.metadataBytes) == size {
529                 return
530         }
531         t.metadataBytes = make([]byte, size)
532         t.metadataCompletedChunks = make([]bool, (size+(1<<14)-1)/(1<<14))
533         t.metadataChanged.Broadcast()
534         for c := range t.conns {
535                 c.requestPendingMetadata()
536         }
537         return
538 }
539
540 // The current working name for the torrent. Either the name in the info dict,
541 // or a display name given such as by the dn value in a magnet link, or "".
542 func (t *Torrent) name() string {
543         t.nameMu.RLock()
544         defer t.nameMu.RUnlock()
545         if t.haveInfo() {
546                 return t.info.BestName()
547         }
548         if t.displayName != "" {
549                 return t.displayName
550         }
551         return "infohash:" + t.infoHash.HexString()
552 }
553
554 func (t *Torrent) pieceState(index pieceIndex) (ret PieceState) {
555         p := &t.pieces[index]
556         ret.Priority = t.piecePriority(index)
557         ret.Completion = p.completion()
558         ret.QueuedForHash = p.queuedForHash()
559         ret.Hashing = p.hashing
560         ret.Checking = ret.QueuedForHash || ret.Hashing
561         ret.Marking = p.marking
562         if !ret.Complete && t.piecePartiallyDownloaded(index) {
563                 ret.Partial = true
564         }
565         return
566 }
567
568 func (t *Torrent) metadataPieceSize(piece int) int {
569         return metadataPieceSize(len(t.metadataBytes), piece)
570 }
571
572 func (t *Torrent) newMetadataExtensionMessage(c *PeerConn, msgType pp.ExtendedMetadataRequestMsgType, piece int, data []byte) pp.Message {
573         return pp.Message{
574                 Type:       pp.Extended,
575                 ExtendedID: c.PeerExtensionIDs[pp.ExtensionNameMetadata],
576                 ExtendedPayload: append(bencode.MustMarshal(pp.ExtendedMetadataRequestMsg{
577                         Piece:     piece,
578                         TotalSize: len(t.metadataBytes),
579                         Type:      msgType,
580                 }), data...),
581         }
582 }
583
584 type pieceAvailabilityRun struct {
585         Count        pieceIndex
586         Availability int
587 }
588
589 func (me pieceAvailabilityRun) String() string {
590         return fmt.Sprintf("%v(%v)", me.Count, me.Availability)
591 }
592
593 func (t *Torrent) pieceAvailabilityRuns() (ret []pieceAvailabilityRun) {
594         rle := missinggo.NewRunLengthEncoder(func(el interface{}, count uint64) {
595                 ret = append(ret, pieceAvailabilityRun{Availability: el.(int), Count: int(count)})
596         })
597         for i := range t.pieces {
598                 rle.Append(t.pieces[i].availability(), 1)
599         }
600         rle.Flush()
601         return
602 }
603
604 func (t *Torrent) pieceAvailabilityFrequencies() (freqs []int) {
605         freqs = make([]int, t.numActivePeers()+1)
606         for i := range t.pieces {
607                 freqs[t.piece(i).availability()]++
608         }
609         return
610 }
611
612 func (t *Torrent) pieceStateRuns() (ret PieceStateRuns) {
613         rle := missinggo.NewRunLengthEncoder(func(el interface{}, count uint64) {
614                 ret = append(ret, PieceStateRun{
615                         PieceState: el.(PieceState),
616                         Length:     int(count),
617                 })
618         })
619         for index := range t.pieces {
620                 rle.Append(t.pieceState(pieceIndex(index)), 1)
621         }
622         rle.Flush()
623         return
624 }
625
626 // Produces a small string representing a PieceStateRun.
627 func (psr PieceStateRun) String() (ret string) {
628         ret = fmt.Sprintf("%d", psr.Length)
629         ret += func() string {
630                 switch psr.Priority {
631                 case PiecePriorityNext:
632                         return "N"
633                 case PiecePriorityNormal:
634                         return "."
635                 case PiecePriorityReadahead:
636                         return "R"
637                 case PiecePriorityNow:
638                         return "!"
639                 case PiecePriorityHigh:
640                         return "H"
641                 default:
642                         return ""
643                 }
644         }()
645         if psr.Hashing {
646                 ret += "H"
647         }
648         if psr.QueuedForHash {
649                 ret += "Q"
650         }
651         if psr.Marking {
652                 ret += "M"
653         }
654         if psr.Partial {
655                 ret += "P"
656         }
657         if psr.Complete {
658                 ret += "C"
659         }
660         if !psr.Ok {
661                 ret += "?"
662         }
663         return
664 }
665
666 func (t *Torrent) writeStatus(w io.Writer) {
667         fmt.Fprintf(w, "Infohash: %s\n", t.infoHash.HexString())
668         fmt.Fprintf(w, "Metadata length: %d\n", t.metadataSize())
669         if !t.haveInfo() {
670                 fmt.Fprintf(w, "Metadata have: ")
671                 for _, h := range t.metadataCompletedChunks {
672                         fmt.Fprintf(w, "%c", func() rune {
673                                 if h {
674                                         return 'H'
675                                 } else {
676                                         return '.'
677                                 }
678                         }())
679                 }
680                 fmt.Fprintln(w)
681         }
682         fmt.Fprintf(w, "Piece length: %s\n",
683                 func() string {
684                         if t.haveInfo() {
685                                 return fmt.Sprintf("%v (%v chunks)",
686                                         t.usualPieceSize(),
687                                         float64(t.usualPieceSize())/float64(t.chunkSize))
688                         } else {
689                                 return "no info"
690                         }
691                 }(),
692         )
693         if t.info != nil {
694                 fmt.Fprintf(w, "Num Pieces: %d (%d completed)\n", t.numPieces(), t.numPiecesCompleted())
695                 fmt.Fprintf(w, "Piece States: %s\n", t.pieceStateRuns())
696                 // Generates a huge, unhelpful listing when piece availability is very scattered. Prefer
697                 // availability frequencies instead.
698                 if false {
699                         fmt.Fprintf(w, "Piece availability: %v\n", strings.Join(func() (ret []string) {
700                                 for _, run := range t.pieceAvailabilityRuns() {
701                                         ret = append(ret, run.String())
702                                 }
703                                 return
704                         }(), " "))
705                 }
706                 fmt.Fprintf(w, "Piece availability frequency: %v\n", strings.Join(
707                         func() (ret []string) {
708                                 for avail, freq := range t.pieceAvailabilityFrequencies() {
709                                         if freq == 0 {
710                                                 continue
711                                         }
712                                         ret = append(ret, fmt.Sprintf("%v: %v", avail, freq))
713                                 }
714                                 return
715                         }(),
716                         ", "))
717         }
718         fmt.Fprintf(w, "Reader Pieces:")
719         t.forReaderOffsetPieces(func(begin, end pieceIndex) (again bool) {
720                 fmt.Fprintf(w, " %d:%d", begin, end)
721                 return true
722         })
723         fmt.Fprintln(w)
724
725         fmt.Fprintf(w, "Enabled trackers:\n")
726         func() {
727                 tw := tabwriter.NewWriter(w, 0, 0, 2, ' ', 0)
728                 fmt.Fprintf(tw, "    URL\tExtra\n")
729                 for _, ta := range slices.Sort(slices.FromMapElems(t.trackerAnnouncers), func(l, r torrentTrackerAnnouncer) bool {
730                         lu := l.URL()
731                         ru := r.URL()
732                         var luns, runs url.URL = *lu, *ru
733                         luns.Scheme = ""
734                         runs.Scheme = ""
735                         var ml missinggo.MultiLess
736                         ml.StrictNext(luns.String() == runs.String(), luns.String() < runs.String())
737                         ml.StrictNext(lu.String() == ru.String(), lu.String() < ru.String())
738                         return ml.Less()
739                 }).([]torrentTrackerAnnouncer) {
740                         fmt.Fprintf(tw, "    %q\t%v\n", ta.URL(), ta.statusLine())
741                 }
742                 tw.Flush()
743         }()
744
745         fmt.Fprintf(w, "DHT Announces: %d\n", t.numDHTAnnounces)
746
747         spew.NewDefaultConfig()
748         spew.Fdump(w, t.statsLocked())
749
750         peers := t.peersAsSlice()
751         sort.Slice(peers, func(_i, _j int) bool {
752                 i := peers[_i]
753                 j := peers[_j]
754                 if less, ok := multiless.New().EagerSameLess(
755                         i.downloadRate() == j.downloadRate(), i.downloadRate() < j.downloadRate(),
756                 ).LessOk(); ok {
757                         return less
758                 }
759                 return worseConn(i, j)
760         })
761         for i, c := range peers {
762                 fmt.Fprintf(w, "%2d. ", i+1)
763                 c.writeStatus(w, t)
764         }
765 }
766
767 func (t *Torrent) haveInfo() bool {
768         return t.info != nil
769 }
770
771 // Returns a run-time generated MetaInfo that includes the info bytes and
772 // announce-list as currently known to the client.
773 func (t *Torrent) newMetaInfo() metainfo.MetaInfo {
774         return metainfo.MetaInfo{
775                 CreationDate: time.Now().Unix(),
776                 Comment:      "dynamic metainfo from client",
777                 CreatedBy:    "go.torrent",
778                 AnnounceList: t.metainfo.UpvertedAnnounceList().Clone(),
779                 InfoBytes: func() []byte {
780                         if t.haveInfo() {
781                                 return t.metadataBytes
782                         } else {
783                                 return nil
784                         }
785                 }(),
786                 UrlList: func() []string {
787                         ret := make([]string, 0, len(t.webSeeds))
788                         for url := range t.webSeeds {
789                                 ret = append(ret, url)
790                         }
791                         return ret
792                 }(),
793         }
794 }
795
796 // Get bytes left
797 func (t *Torrent) BytesMissing() (n int64) {
798         t.cl.rLock()
799         n = t.bytesMissingLocked()
800         t.cl.rUnlock()
801         return
802 }
803
804 func (t *Torrent) bytesMissingLocked() int64 {
805         return t.bytesLeft()
806 }
807
808 func iterFlipped(b *roaring.Bitmap, end uint64, cb func(uint32) bool) {
809         roaring.Flip(b, 0, end).Iterate(cb)
810 }
811
812 func (t *Torrent) bytesLeft() (left int64) {
813         iterFlipped(&t._completedPieces, uint64(t.numPieces()), func(x uint32) bool {
814                 p := t.piece(pieceIndex(x))
815                 left += int64(p.length() - p.numDirtyBytes())
816                 return true
817         })
818         return
819 }
820
821 // Bytes left to give in tracker announces.
822 func (t *Torrent) bytesLeftAnnounce() int64 {
823         if t.haveInfo() {
824                 return t.bytesLeft()
825         } else {
826                 return -1
827         }
828 }
829
830 func (t *Torrent) piecePartiallyDownloaded(piece pieceIndex) bool {
831         if t.pieceComplete(piece) {
832                 return false
833         }
834         if t.pieceAllDirty(piece) {
835                 return false
836         }
837         return t.pieces[piece].hasDirtyChunks()
838 }
839
840 func (t *Torrent) usualPieceSize() int {
841         return int(t.info.PieceLength)
842 }
843
844 func (t *Torrent) numPieces() pieceIndex {
845         return pieceIndex(t.info.NumPieces())
846 }
847
848 func (t *Torrent) numPiecesCompleted() (num pieceIndex) {
849         return pieceIndex(t._completedPieces.GetCardinality())
850 }
851
852 func (t *Torrent) close(wg *sync.WaitGroup) (err error) {
853         if !t.closed.Set() {
854                 err = errors.New("already closed")
855                 return
856         }
857         if t.storage != nil {
858                 wg.Add(1)
859                 go func() {
860                         defer wg.Done()
861                         t.storageLock.Lock()
862                         defer t.storageLock.Unlock()
863                         if f := t.storage.Close; f != nil {
864                                 err1 := f()
865                                 if err1 != nil {
866                                         t.logger.WithDefaultLevel(log.Warning).Printf("error closing storage: %v", err1)
867                                 }
868                         }
869                 }()
870         }
871         t.iterPeers(func(p *Peer) {
872                 p.close()
873         })
874         if t.storage != nil {
875                 t.deletePieceRequestOrder()
876         }
877         for i := range t.pieces {
878                 p := t.piece(i)
879                 if p.relativeAvailability != 0 {
880                         panic(fmt.Sprintf("piece %v has relative availability %v", i, p.relativeAvailability))
881                 }
882         }
883         t.pex.Reset()
884         t.cl.event.Broadcast()
885         t.pieceStateChanges.Close()
886         t.updateWantPeersEvent()
887         return
888 }
889
890 func (t *Torrent) requestOffset(r Request) int64 {
891         return torrentRequestOffset(*t.length, int64(t.usualPieceSize()), r)
892 }
893
894 // Return the request that would include the given offset into the torrent data. Returns !ok if
895 // there is no such request.
896 func (t *Torrent) offsetRequest(off int64) (req Request, ok bool) {
897         return torrentOffsetRequest(*t.length, t.info.PieceLength, int64(t.chunkSize), off)
898 }
899
900 func (t *Torrent) writeChunk(piece int, begin int64, data []byte) (err error) {
901         defer perf.ScopeTimerErr(&err)()
902         n, err := t.pieces[piece].Storage().WriteAt(data, begin)
903         if err == nil && n != len(data) {
904                 err = io.ErrShortWrite
905         }
906         return err
907 }
908
909 func (t *Torrent) bitfield() (bf []bool) {
910         bf = make([]bool, t.numPieces())
911         t._completedPieces.Iterate(func(piece uint32) (again bool) {
912                 bf[piece] = true
913                 return true
914         })
915         return
916 }
917
918 func (t *Torrent) pieceNumChunks(piece pieceIndex) chunkIndexType {
919         return chunkIndexType((t.pieceLength(piece) + t.chunkSize - 1) / t.chunkSize)
920 }
921
922 func (t *Torrent) chunksPerRegularPiece() uint32 {
923         return uint32((pp.Integer(t.usualPieceSize()) + t.chunkSize - 1) / t.chunkSize)
924 }
925
926 func (t *Torrent) numRequests() RequestIndex {
927         if t.numPieces() == 0 {
928                 return 0
929         }
930         return uint32(t.numPieces()-1)*t.chunksPerRegularPiece() + t.pieceNumChunks(t.numPieces()-1)
931 }
932
933 func (t *Torrent) pendAllChunkSpecs(pieceIndex pieceIndex) {
934         t.dirtyChunks.RemoveRange(
935                 uint64(t.pieceRequestIndexOffset(pieceIndex)),
936                 uint64(t.pieceRequestIndexOffset(pieceIndex+1)))
937 }
938
939 func (t *Torrent) pieceLength(piece pieceIndex) pp.Integer {
940         if t.info.PieceLength == 0 {
941                 // There will be no variance amongst pieces. Only pain.
942                 return 0
943         }
944         if piece == t.numPieces()-1 {
945                 ret := pp.Integer(*t.length % t.info.PieceLength)
946                 if ret != 0 {
947                         return ret
948                 }
949         }
950         return pp.Integer(t.info.PieceLength)
951 }
952
953 func (t *Torrent) smartBanBlockCheckingWriter(piece pieceIndex) *blockCheckingWriter {
954         return &blockCheckingWriter{
955                 cache:        &t.smartBanCache,
956                 requestIndex: t.pieceRequestIndexOffset(piece),
957                 chunkSize:    t.chunkSize.Int(),
958         }
959 }
960
961 func (t *Torrent) hashPiece(piece pieceIndex) (
962         ret metainfo.Hash,
963         // These are peers that sent us blocks that differ from what we hash here.
964         differingPeers map[bannableAddr]struct{},
965         err error,
966 ) {
967         p := t.piece(piece)
968         p.waitNoPendingWrites()
969         storagePiece := t.pieces[piece].Storage()
970
971         // Does the backend want to do its own hashing?
972         if i, ok := storagePiece.PieceImpl.(storage.SelfHashing); ok {
973                 var sum metainfo.Hash
974                 // log.Printf("A piece decided to self-hash: %d", piece)
975                 sum, err = i.SelfHash()
976                 missinggo.CopyExact(&ret, sum)
977                 return
978         }
979
980         hash := pieceHash.New()
981         const logPieceContents = false
982         smartBanWriter := t.smartBanBlockCheckingWriter(piece)
983         writers := []io.Writer{hash, smartBanWriter}
984         var examineBuf bytes.Buffer
985         if logPieceContents {
986                 writers = append(writers, &examineBuf)
987         }
988         _, err = storagePiece.WriteTo(io.MultiWriter(writers...))
989         if logPieceContents {
990                 log.Printf("hashed %q with copy err %v", examineBuf.Bytes(), err)
991         }
992         smartBanWriter.Flush()
993         differingPeers = smartBanWriter.badPeers
994         missinggo.CopyExact(&ret, hash.Sum(nil))
995         return
996 }
997
998 func (t *Torrent) haveAnyPieces() bool {
999         return !t._completedPieces.IsEmpty()
1000 }
1001
1002 func (t *Torrent) haveAllPieces() bool {
1003         if !t.haveInfo() {
1004                 return false
1005         }
1006         return t._completedPieces.GetCardinality() == bitmap.BitRange(t.numPieces())
1007 }
1008
1009 func (t *Torrent) havePiece(index pieceIndex) bool {
1010         return t.haveInfo() && t.pieceComplete(index)
1011 }
1012
1013 func (t *Torrent) maybeDropMutuallyCompletePeer(
1014         // I'm not sure about taking peer here, not all peer implementations actually drop. Maybe that's
1015         // okay?
1016         p *Peer,
1017 ) {
1018         if !t.cl.config.DropMutuallyCompletePeers {
1019                 return
1020         }
1021         if !t.haveAllPieces() {
1022                 return
1023         }
1024         if all, known := p.peerHasAllPieces(); !(known && all) {
1025                 return
1026         }
1027         if p.useful() {
1028                 return
1029         }
1030         t.logger.WithDefaultLevel(log.Debug).Printf("dropping %v, which is mutually complete", p)
1031         p.drop()
1032 }
1033
1034 func (t *Torrent) haveChunk(r Request) (ret bool) {
1035         // defer func() {
1036         //      log.Println("have chunk", r, ret)
1037         // }()
1038         if !t.haveInfo() {
1039                 return false
1040         }
1041         if t.pieceComplete(pieceIndex(r.Index)) {
1042                 return true
1043         }
1044         p := &t.pieces[r.Index]
1045         return !p.pendingChunk(r.ChunkSpec, t.chunkSize)
1046 }
1047
1048 func chunkIndexFromChunkSpec(cs ChunkSpec, chunkSize pp.Integer) chunkIndexType {
1049         return chunkIndexType(cs.Begin / chunkSize)
1050 }
1051
1052 func (t *Torrent) wantPieceIndex(index pieceIndex) bool {
1053         return t._pendingPieces.Contains(uint32(index))
1054 }
1055
1056 // A pool of []*PeerConn, to reduce allocations in functions that need to index or sort Torrent
1057 // conns (which is a map).
1058 var peerConnSlices sync.Pool
1059
1060 func getPeerConnSlice(cap int) []*PeerConn {
1061         getInterface := peerConnSlices.Get()
1062         if getInterface == nil {
1063                 return make([]*PeerConn, 0, cap)
1064         } else {
1065                 return getInterface.([]*PeerConn)[:0]
1066         }
1067 }
1068
1069 // The worst connection is one that hasn't been sent, or sent anything useful for the longest. A bad
1070 // connection is one that usually sends us unwanted pieces, or has been in the worse half of the
1071 // established connections for more than a minute. This is O(n log n). If there was a way to not
1072 // consider the position of a conn relative to the total number, it could be reduced to O(n).
1073 func (t *Torrent) worstBadConn() (ret *PeerConn) {
1074         wcs := worseConnSlice{conns: t.appendUnclosedConns(getPeerConnSlice(len(t.conns)))}
1075         defer peerConnSlices.Put(wcs.conns)
1076         wcs.initKeys()
1077         heap.Init(&wcs)
1078         for wcs.Len() != 0 {
1079                 c := heap.Pop(&wcs).(*PeerConn)
1080                 if c._stats.ChunksReadWasted.Int64() >= 6 && c._stats.ChunksReadWasted.Int64() > c._stats.ChunksReadUseful.Int64() {
1081                         return c
1082                 }
1083                 // If the connection is in the worst half of the established
1084                 // connection quota and is older than a minute.
1085                 if wcs.Len() >= (t.maxEstablishedConns+1)/2 {
1086                         // Give connections 1 minute to prove themselves.
1087                         if time.Since(c.completedHandshake) > time.Minute {
1088                                 return c
1089                         }
1090                 }
1091         }
1092         return nil
1093 }
1094
1095 type PieceStateChange struct {
1096         Index int
1097         PieceState
1098 }
1099
1100 func (t *Torrent) publishPieceChange(piece pieceIndex) {
1101         t.cl._mu.Defer(func() {
1102                 cur := t.pieceState(piece)
1103                 p := &t.pieces[piece]
1104                 if cur != p.publicPieceState {
1105                         p.publicPieceState = cur
1106                         t.pieceStateChanges.Publish(PieceStateChange{
1107                                 int(piece),
1108                                 cur,
1109                         })
1110                 }
1111         })
1112 }
1113
1114 func (t *Torrent) pieceNumPendingChunks(piece pieceIndex) pp.Integer {
1115         if t.pieceComplete(piece) {
1116                 return 0
1117         }
1118         return pp.Integer(t.pieceNumChunks(piece) - t.pieces[piece].numDirtyChunks())
1119 }
1120
1121 func (t *Torrent) pieceAllDirty(piece pieceIndex) bool {
1122         return t.pieces[piece].allChunksDirty()
1123 }
1124
1125 func (t *Torrent) readersChanged() {
1126         t.updateReaderPieces()
1127         t.updateAllPiecePriorities("Torrent.readersChanged")
1128 }
1129
1130 func (t *Torrent) updateReaderPieces() {
1131         t._readerNowPieces, t._readerReadaheadPieces = t.readerPiecePriorities()
1132 }
1133
1134 func (t *Torrent) readerPosChanged(from, to pieceRange) {
1135         if from == to {
1136                 return
1137         }
1138         t.updateReaderPieces()
1139         // Order the ranges, high and low.
1140         l, h := from, to
1141         if l.begin > h.begin {
1142                 l, h = h, l
1143         }
1144         if l.end < h.begin {
1145                 // Two distinct ranges.
1146                 t.updatePiecePriorities(l.begin, l.end, "Torrent.readerPosChanged")
1147                 t.updatePiecePriorities(h.begin, h.end, "Torrent.readerPosChanged")
1148         } else {
1149                 // Ranges overlap.
1150                 end := l.end
1151                 if h.end > end {
1152                         end = h.end
1153                 }
1154                 t.updatePiecePriorities(l.begin, end, "Torrent.readerPosChanged")
1155         }
1156 }
1157
1158 func (t *Torrent) maybeNewConns() {
1159         // Tickle the accept routine.
1160         t.cl.event.Broadcast()
1161         t.openNewConns()
1162 }
1163
1164 func (t *Torrent) piecePriorityChanged(piece pieceIndex, reason string) {
1165         if t._pendingPieces.Contains(uint32(piece)) {
1166                 t.iterPeers(func(c *Peer) {
1167                         // if c.requestState.Interested {
1168                         //      return
1169                         // }
1170                         if !c.isLowOnRequests() {
1171                                 return
1172                         }
1173                         if !c.peerHasPiece(piece) {
1174                                 return
1175                         }
1176                         if c.requestState.Interested && c.peerChoking && !c.peerAllowedFast.Contains(uint32(piece)) {
1177                                 return
1178                         }
1179                         c.updateRequests(reason)
1180                 })
1181         }
1182         t.maybeNewConns()
1183         t.publishPieceChange(piece)
1184 }
1185
1186 func (t *Torrent) updatePiecePriority(piece pieceIndex, reason string) {
1187         if !t.closed.IsSet() {
1188                 // It would be possible to filter on pure-priority changes here to avoid churning the piece
1189                 // request order.
1190                 t.updatePieceRequestOrder(piece)
1191         }
1192         p := &t.pieces[piece]
1193         newPrio := p.uncachedPriority()
1194         // t.logger.Printf("torrent %p: piece %d: uncached priority: %v", t, piece, newPrio)
1195         if newPrio == PiecePriorityNone {
1196                 if !t._pendingPieces.CheckedRemove(uint32(piece)) {
1197                         return
1198                 }
1199         } else {
1200                 if !t._pendingPieces.CheckedAdd(uint32(piece)) {
1201                         return
1202                 }
1203         }
1204         t.piecePriorityChanged(piece, reason)
1205 }
1206
1207 func (t *Torrent) updateAllPiecePriorities(reason string) {
1208         t.updatePiecePriorities(0, t.numPieces(), reason)
1209 }
1210
1211 // Update all piece priorities in one hit. This function should have the same
1212 // output as updatePiecePriority, but across all pieces.
1213 func (t *Torrent) updatePiecePriorities(begin, end pieceIndex, reason string) {
1214         for i := begin; i < end; i++ {
1215                 t.updatePiecePriority(i, reason)
1216         }
1217 }
1218
1219 // Returns the range of pieces [begin, end) that contains the extent of bytes.
1220 func (t *Torrent) byteRegionPieces(off, size int64) (begin, end pieceIndex) {
1221         if off >= *t.length {
1222                 return
1223         }
1224         if off < 0 {
1225                 size += off
1226                 off = 0
1227         }
1228         if size <= 0 {
1229                 return
1230         }
1231         begin = pieceIndex(off / t.info.PieceLength)
1232         end = pieceIndex((off + size + t.info.PieceLength - 1) / t.info.PieceLength)
1233         if end > pieceIndex(t.info.NumPieces()) {
1234                 end = pieceIndex(t.info.NumPieces())
1235         }
1236         return
1237 }
1238
1239 // Returns true if all iterations complete without breaking. Returns the read regions for all
1240 // readers. The reader regions should not be merged as some callers depend on this method to
1241 // enumerate readers.
1242 func (t *Torrent) forReaderOffsetPieces(f func(begin, end pieceIndex) (more bool)) (all bool) {
1243         for r := range t.readers {
1244                 p := r.pieces
1245                 if p.begin >= p.end {
1246                         continue
1247                 }
1248                 if !f(p.begin, p.end) {
1249                         return false
1250                 }
1251         }
1252         return true
1253 }
1254
1255 func (t *Torrent) piecePriority(piece pieceIndex) piecePriority {
1256         return t.piece(piece).uncachedPriority()
1257 }
1258
1259 func (t *Torrent) pendRequest(req RequestIndex) {
1260         t.piece(int(req / t.chunksPerRegularPiece())).pendChunkIndex(req % t.chunksPerRegularPiece())
1261 }
1262
1263 func (t *Torrent) pieceCompletionChanged(piece pieceIndex, reason string) {
1264         t.cl.event.Broadcast()
1265         if t.pieceComplete(piece) {
1266                 t.onPieceCompleted(piece)
1267         } else {
1268                 t.onIncompletePiece(piece)
1269         }
1270         t.updatePiecePriority(piece, reason)
1271 }
1272
1273 func (t *Torrent) numReceivedConns() (ret int) {
1274         for c := range t.conns {
1275                 if c.Discovery == PeerSourceIncoming {
1276                         ret++
1277                 }
1278         }
1279         return
1280 }
1281
1282 func (t *Torrent) maxHalfOpen() int {
1283         // Note that if we somehow exceed the maximum established conns, we want
1284         // the negative value to have an effect.
1285         establishedHeadroom := int64(t.maxEstablishedConns - len(t.conns))
1286         extraIncoming := int64(t.numReceivedConns() - t.maxEstablishedConns/2)
1287         // We want to allow some experimentation with new peers, and to try to
1288         // upset an oversupply of received connections.
1289         return int(min(max(5, extraIncoming)+establishedHeadroom, int64(t.cl.config.HalfOpenConnsPerTorrent)))
1290 }
1291
1292 func (t *Torrent) openNewConns() (initiated int) {
1293         defer t.updateWantPeersEvent()
1294         for t.peers.Len() != 0 {
1295                 if !t.wantConns() {
1296                         return
1297                 }
1298                 if len(t.halfOpen) >= t.maxHalfOpen() {
1299                         return
1300                 }
1301                 if len(t.cl.dialers) == 0 {
1302                         return
1303                 }
1304                 if t.cl.numHalfOpen >= t.cl.config.TotalHalfOpenConns {
1305                         return
1306                 }
1307                 p := t.peers.PopMax()
1308                 t.initiateConn(p)
1309                 initiated++
1310         }
1311         return
1312 }
1313
1314 func (t *Torrent) updatePieceCompletion(piece pieceIndex) bool {
1315         p := t.piece(piece)
1316         uncached := t.pieceCompleteUncached(piece)
1317         cached := p.completion()
1318         changed := cached != uncached
1319         complete := uncached.Complete
1320         p.storageCompletionOk = uncached.Ok
1321         x := uint32(piece)
1322         if complete {
1323                 t._completedPieces.Add(x)
1324                 t.openNewConns()
1325         } else {
1326                 t._completedPieces.Remove(x)
1327         }
1328         p.t.updatePieceRequestOrder(piece)
1329         t.updateComplete()
1330         if complete && len(p.dirtiers) != 0 {
1331                 t.logger.Printf("marked piece %v complete but still has dirtiers", piece)
1332         }
1333         if changed {
1334                 log.Fstr("piece %d completion changed: %+v -> %+v", piece, cached, uncached).LogLevel(log.Debug, t.logger)
1335                 t.pieceCompletionChanged(piece, "Torrent.updatePieceCompletion")
1336         }
1337         return changed
1338 }
1339
1340 // Non-blocking read. Client lock is not required.
1341 func (t *Torrent) readAt(b []byte, off int64) (n int, err error) {
1342         for len(b) != 0 {
1343                 p := &t.pieces[off/t.info.PieceLength]
1344                 p.waitNoPendingWrites()
1345                 var n1 int
1346                 n1, err = p.Storage().ReadAt(b, off-p.Info().Offset())
1347                 if n1 == 0 {
1348                         break
1349                 }
1350                 off += int64(n1)
1351                 n += n1
1352                 b = b[n1:]
1353         }
1354         return
1355 }
1356
1357 // Returns an error if the metadata was completed, but couldn't be set for some reason. Blame it on
1358 // the last peer to contribute. TODO: Actually we shouldn't blame peers for failure to open storage
1359 // etc. Also we should probably cached metadata pieces per-Peer, to isolate failure appropriately.
1360 func (t *Torrent) maybeCompleteMetadata() error {
1361         if t.haveInfo() {
1362                 // Nothing to do.
1363                 return nil
1364         }
1365         if !t.haveAllMetadataPieces() {
1366                 // Don't have enough metadata pieces.
1367                 return nil
1368         }
1369         err := t.setInfoBytesLocked(t.metadataBytes)
1370         if err != nil {
1371                 t.invalidateMetadata()
1372                 return fmt.Errorf("error setting info bytes: %s", err)
1373         }
1374         if t.cl.config.Debug {
1375                 t.logger.Printf("%s: got metadata from peers", t)
1376         }
1377         return nil
1378 }
1379
1380 func (t *Torrent) readerPiecePriorities() (now, readahead bitmap.Bitmap) {
1381         t.forReaderOffsetPieces(func(begin, end pieceIndex) bool {
1382                 if end > begin {
1383                         now.Add(bitmap.BitIndex(begin))
1384                         readahead.AddRange(bitmap.BitRange(begin)+1, bitmap.BitRange(end))
1385                 }
1386                 return true
1387         })
1388         return
1389 }
1390
1391 func (t *Torrent) needData() bool {
1392         if t.closed.IsSet() {
1393                 return false
1394         }
1395         if !t.haveInfo() {
1396                 return true
1397         }
1398         return !t._pendingPieces.IsEmpty()
1399 }
1400
1401 func appendMissingStrings(old, new []string) (ret []string) {
1402         ret = old
1403 new:
1404         for _, n := range new {
1405                 for _, o := range old {
1406                         if o == n {
1407                                 continue new
1408                         }
1409                 }
1410                 ret = append(ret, n)
1411         }
1412         return
1413 }
1414
1415 func appendMissingTrackerTiers(existing [][]string, minNumTiers int) (ret [][]string) {
1416         ret = existing
1417         for minNumTiers > len(ret) {
1418                 ret = append(ret, nil)
1419         }
1420         return
1421 }
1422
1423 func (t *Torrent) addTrackers(announceList [][]string) {
1424         fullAnnounceList := &t.metainfo.AnnounceList
1425         t.metainfo.AnnounceList = appendMissingTrackerTiers(*fullAnnounceList, len(announceList))
1426         for tierIndex, trackerURLs := range announceList {
1427                 (*fullAnnounceList)[tierIndex] = appendMissingStrings((*fullAnnounceList)[tierIndex], trackerURLs)
1428         }
1429         t.startMissingTrackerScrapers()
1430         t.updateWantPeersEvent()
1431 }
1432
1433 // Don't call this before the info is available.
1434 func (t *Torrent) bytesCompleted() int64 {
1435         if !t.haveInfo() {
1436                 return 0
1437         }
1438         return *t.length - t.bytesLeft()
1439 }
1440
1441 func (t *Torrent) SetInfoBytes(b []byte) (err error) {
1442         t.cl.lock()
1443         defer t.cl.unlock()
1444         return t.setInfoBytesLocked(b)
1445 }
1446
1447 // Returns true if connection is removed from torrent.Conns.
1448 func (t *Torrent) deletePeerConn(c *PeerConn) (ret bool) {
1449         if !c.closed.IsSet() {
1450                 panic("connection is not closed")
1451                 // There are behaviours prevented by the closed state that will fail
1452                 // if the connection has been deleted.
1453         }
1454         _, ret = t.conns[c]
1455         delete(t.conns, c)
1456         // Avoid adding a drop event more than once. Probably we should track whether we've generated
1457         // the drop event against the PexConnState instead.
1458         if ret {
1459                 if !t.cl.config.DisablePEX {
1460                         t.pex.Drop(c)
1461                 }
1462         }
1463         torrent.Add("deleted connections", 1)
1464         if !c.deleteAllRequests().IsEmpty() {
1465                 t.iterPeers(func(p *Peer) {
1466                         if p.isLowOnRequests() {
1467                                 p.updateRequests("Torrent.deletePeerConn")
1468                         }
1469                 })
1470         }
1471         t.assertPendingRequests()
1472         if t.numActivePeers() == 0 && len(t.connsWithAllPieces) != 0 {
1473                 panic(t.connsWithAllPieces)
1474         }
1475         return
1476 }
1477
1478 func (t *Torrent) decPeerPieceAvailability(p *Peer) {
1479         if t.deleteConnWithAllPieces(p) {
1480                 return
1481         }
1482         if !t.haveInfo() {
1483                 return
1484         }
1485         p.peerPieces().Iterate(func(i uint32) bool {
1486                 p.t.decPieceAvailability(pieceIndex(i))
1487                 return true
1488         })
1489 }
1490
1491 func (t *Torrent) assertPendingRequests() {
1492         if !check {
1493                 return
1494         }
1495         // var actual pendingRequests
1496         // if t.haveInfo() {
1497         //      actual.m = make([]int, t.numRequests())
1498         // }
1499         // t.iterPeers(func(p *Peer) {
1500         //      p.requestState.Requests.Iterate(func(x uint32) bool {
1501         //              actual.Inc(x)
1502         //              return true
1503         //      })
1504         // })
1505         // diff := cmp.Diff(actual.m, t.pendingRequests.m)
1506         // if diff != "" {
1507         //      panic(diff)
1508         // }
1509 }
1510
1511 func (t *Torrent) dropConnection(c *PeerConn) {
1512         t.cl.event.Broadcast()
1513         c.close()
1514         if t.deletePeerConn(c) {
1515                 t.openNewConns()
1516         }
1517 }
1518
1519 // Peers as in contact information for dialing out.
1520 func (t *Torrent) wantPeers() bool {
1521         if t.closed.IsSet() {
1522                 return false
1523         }
1524         if t.peers.Len() > t.cl.config.TorrentPeersLowWater {
1525                 return false
1526         }
1527         return t.wantConns()
1528 }
1529
1530 func (t *Torrent) updateWantPeersEvent() {
1531         if t.wantPeers() {
1532                 t.wantPeersEvent.Set()
1533         } else {
1534                 t.wantPeersEvent.Clear()
1535         }
1536 }
1537
1538 // Returns whether the client should make effort to seed the torrent.
1539 func (t *Torrent) seeding() bool {
1540         cl := t.cl
1541         if t.closed.IsSet() {
1542                 return false
1543         }
1544         if t.dataUploadDisallowed {
1545                 return false
1546         }
1547         if cl.config.NoUpload {
1548                 return false
1549         }
1550         if !cl.config.Seed {
1551                 return false
1552         }
1553         if cl.config.DisableAggressiveUpload && t.needData() {
1554                 return false
1555         }
1556         return true
1557 }
1558
1559 func (t *Torrent) onWebRtcConn(
1560         c datachannel.ReadWriteCloser,
1561         dcc webtorrent.DataChannelContext,
1562 ) {
1563         defer c.Close()
1564         netConn := webrtcNetConn{
1565                 ReadWriteCloser:    c,
1566                 DataChannelContext: dcc,
1567         }
1568         peerRemoteAddr := netConn.RemoteAddr()
1569         if t.cl.badPeerAddr(peerRemoteAddr) {
1570                 return
1571         }
1572         pc, err := t.cl.initiateProtocolHandshakes(
1573                 context.Background(),
1574                 netConn,
1575                 t,
1576                 dcc.LocalOffered,
1577                 false,
1578                 netConn.RemoteAddr(),
1579                 webrtcNetwork,
1580                 fmt.Sprintf("webrtc offer_id %x: %v", dcc.OfferId, regularNetConnPeerConnConnString(netConn)),
1581         )
1582         if err != nil {
1583                 t.logger.WithDefaultLevel(log.Error).Printf("error in handshaking webrtc connection: %v", err)
1584                 return
1585         }
1586         if dcc.LocalOffered {
1587                 pc.Discovery = PeerSourceTracker
1588         } else {
1589                 pc.Discovery = PeerSourceIncoming
1590         }
1591         pc.conn.SetWriteDeadline(time.Time{})
1592         t.cl.lock()
1593         defer t.cl.unlock()
1594         err = t.cl.runHandshookConn(pc, t)
1595         if err != nil {
1596                 t.logger.WithDefaultLevel(log.Critical).Printf("error running handshook webrtc conn: %v", err)
1597         }
1598 }
1599
1600 func (t *Torrent) logRunHandshookConn(pc *PeerConn, logAll bool, level log.Level) {
1601         err := t.cl.runHandshookConn(pc, t)
1602         if err != nil || logAll {
1603                 t.logger.WithDefaultLevel(level).Printf("error running handshook conn: %v", err)
1604         }
1605 }
1606
1607 func (t *Torrent) runHandshookConnLoggingErr(pc *PeerConn) {
1608         t.logRunHandshookConn(pc, false, log.Debug)
1609 }
1610
1611 func (t *Torrent) startWebsocketAnnouncer(u url.URL) torrentTrackerAnnouncer {
1612         wtc, release := t.cl.websocketTrackers.Get(u.String())
1613         go func() {
1614                 <-t.closed.Done()
1615                 release()
1616         }()
1617         wst := websocketTrackerStatus{u, wtc}
1618         go func() {
1619                 err := wtc.Announce(tracker.Started, t.infoHash)
1620                 if err != nil {
1621                         t.logger.WithDefaultLevel(log.Warning).Printf(
1622                                 "error in initial announce to %q: %v",
1623                                 u.String(), err,
1624                         )
1625                 }
1626         }()
1627         return wst
1628 }
1629
1630 func (t *Torrent) startScrapingTracker(_url string) {
1631         if _url == "" {
1632                 return
1633         }
1634         u, err := url.Parse(_url)
1635         if err != nil {
1636                 // URLs with a leading '*' appear to be a uTorrent convention to
1637                 // disable trackers.
1638                 if _url[0] != '*' {
1639                         log.Str("error parsing tracker url").AddValues("url", _url).Log(t.logger)
1640                 }
1641                 return
1642         }
1643         if u.Scheme == "udp" {
1644                 u.Scheme = "udp4"
1645                 t.startScrapingTracker(u.String())
1646                 u.Scheme = "udp6"
1647                 t.startScrapingTracker(u.String())
1648                 return
1649         }
1650         if _, ok := t.trackerAnnouncers[_url]; ok {
1651                 return
1652         }
1653         sl := func() torrentTrackerAnnouncer {
1654                 switch u.Scheme {
1655                 case "ws", "wss":
1656                         if t.cl.config.DisableWebtorrent {
1657                                 return nil
1658                         }
1659                         return t.startWebsocketAnnouncer(*u)
1660                 case "udp4":
1661                         if t.cl.config.DisableIPv4Peers || t.cl.config.DisableIPv4 {
1662                                 return nil
1663                         }
1664                 case "udp6":
1665                         if t.cl.config.DisableIPv6 {
1666                                 return nil
1667                         }
1668                 }
1669                 newAnnouncer := &trackerScraper{
1670                         u:               *u,
1671                         t:               t,
1672                         lookupTrackerIp: t.cl.config.LookupTrackerIp,
1673                 }
1674                 go newAnnouncer.Run()
1675                 return newAnnouncer
1676         }()
1677         if sl == nil {
1678                 return
1679         }
1680         if t.trackerAnnouncers == nil {
1681                 t.trackerAnnouncers = make(map[string]torrentTrackerAnnouncer)
1682         }
1683         t.trackerAnnouncers[_url] = sl
1684 }
1685
1686 // Adds and starts tracker scrapers for tracker URLs that aren't already
1687 // running.
1688 func (t *Torrent) startMissingTrackerScrapers() {
1689         if t.cl.config.DisableTrackers {
1690                 return
1691         }
1692         t.startScrapingTracker(t.metainfo.Announce)
1693         for _, tier := range t.metainfo.AnnounceList {
1694                 for _, url := range tier {
1695                         t.startScrapingTracker(url)
1696                 }
1697         }
1698 }
1699
1700 // Returns an AnnounceRequest with fields filled out to defaults and current
1701 // values.
1702 func (t *Torrent) announceRequest(event tracker.AnnounceEvent) tracker.AnnounceRequest {
1703         // Note that IPAddress is not set. It's set for UDP inside the tracker code, since it's
1704         // dependent on the network in use.
1705         return tracker.AnnounceRequest{
1706                 Event: event,
1707                 NumWant: func() int32 {
1708                         if t.wantPeers() && len(t.cl.dialers) > 0 {
1709                                 return -1
1710                         } else {
1711                                 return 0
1712                         }
1713                 }(),
1714                 Port:     uint16(t.cl.incomingPeerPort()),
1715                 PeerId:   t.cl.peerID,
1716                 InfoHash: t.infoHash,
1717                 Key:      t.cl.announceKey(),
1718
1719                 // The following are vaguely described in BEP 3.
1720
1721                 Left:     t.bytesLeftAnnounce(),
1722                 Uploaded: t.stats.BytesWrittenData.Int64(),
1723                 // There's no mention of wasted or unwanted download in the BEP.
1724                 Downloaded: t.stats.BytesReadUsefulData.Int64(),
1725         }
1726 }
1727
1728 // Adds peers revealed in an announce until the announce ends, or we have
1729 // enough peers.
1730 func (t *Torrent) consumeDhtAnnouncePeers(pvs <-chan dht.PeersValues) {
1731         cl := t.cl
1732         for v := range pvs {
1733                 cl.lock()
1734                 added := 0
1735                 for _, cp := range v.Peers {
1736                         if cp.Port == 0 {
1737                                 // Can't do anything with this.
1738                                 continue
1739                         }
1740                         if t.addPeer(PeerInfo{
1741                                 Addr:   ipPortAddr{cp.IP, cp.Port},
1742                                 Source: PeerSourceDhtGetPeers,
1743                         }) {
1744                                 added++
1745                         }
1746                 }
1747                 cl.unlock()
1748                 // if added != 0 {
1749                 //      log.Printf("added %v peers from dht for %v", added, t.InfoHash().HexString())
1750                 // }
1751         }
1752 }
1753
1754 // Announce using the provided DHT server. Peers are consumed automatically. done is closed when the
1755 // announce ends. stop will force the announce to end.
1756 func (t *Torrent) AnnounceToDht(s DhtServer) (done <-chan struct{}, stop func(), err error) {
1757         ps, err := s.Announce(t.infoHash, t.cl.incomingPeerPort(), true)
1758         if err != nil {
1759                 return
1760         }
1761         _done := make(chan struct{})
1762         done = _done
1763         stop = ps.Close
1764         go func() {
1765                 t.consumeDhtAnnouncePeers(ps.Peers())
1766                 close(_done)
1767         }()
1768         return
1769 }
1770
1771 func (t *Torrent) timeboxedAnnounceToDht(s DhtServer) error {
1772         _, stop, err := t.AnnounceToDht(s)
1773         if err != nil {
1774                 return err
1775         }
1776         select {
1777         case <-t.closed.Done():
1778         case <-time.After(5 * time.Minute):
1779         }
1780         stop()
1781         return nil
1782 }
1783
1784 func (t *Torrent) dhtAnnouncer(s DhtServer) {
1785         cl := t.cl
1786         cl.lock()
1787         defer cl.unlock()
1788         for {
1789                 for {
1790                         if t.closed.IsSet() {
1791                                 return
1792                         }
1793                         // We're also announcing ourselves as a listener, so we don't just want peer addresses.
1794                         // TODO: We can include the announce_peer step depending on whether we can receive
1795                         // inbound connections. We should probably only announce once every 15 mins too.
1796                         if !t.wantConns() {
1797                                 goto wait
1798                         }
1799                         // TODO: Determine if there's a listener on the port we're announcing.
1800                         if len(cl.dialers) == 0 && len(cl.listeners) == 0 {
1801                                 goto wait
1802                         }
1803                         break
1804                 wait:
1805                         cl.event.Wait()
1806                 }
1807                 func() {
1808                         t.numDHTAnnounces++
1809                         cl.unlock()
1810                         defer cl.lock()
1811                         err := t.timeboxedAnnounceToDht(s)
1812                         if err != nil {
1813                                 t.logger.WithDefaultLevel(log.Warning).Printf("error announcing %q to DHT: %s", t, err)
1814                         }
1815                 }()
1816         }
1817 }
1818
1819 func (t *Torrent) addPeers(peers []PeerInfo) (added int) {
1820         for _, p := range peers {
1821                 if t.addPeer(p) {
1822                         added++
1823                 }
1824         }
1825         return
1826 }
1827
1828 // The returned TorrentStats may require alignment in memory. See
1829 // https://github.com/anacrolix/torrent/issues/383.
1830 func (t *Torrent) Stats() TorrentStats {
1831         t.cl.rLock()
1832         defer t.cl.rUnlock()
1833         return t.statsLocked()
1834 }
1835
1836 func (t *Torrent) statsLocked() (ret TorrentStats) {
1837         ret.ActivePeers = len(t.conns)
1838         ret.HalfOpenPeers = len(t.halfOpen)
1839         ret.PendingPeers = t.peers.Len()
1840         ret.TotalPeers = t.numTotalPeers()
1841         ret.ConnectedSeeders = 0
1842         for c := range t.conns {
1843                 if all, ok := c.peerHasAllPieces(); all && ok {
1844                         ret.ConnectedSeeders++
1845                 }
1846         }
1847         ret.ConnStats = t.stats.Copy()
1848         ret.PiecesComplete = t.numPiecesCompleted()
1849         return
1850 }
1851
1852 // The total number of peers in the torrent.
1853 func (t *Torrent) numTotalPeers() int {
1854         peers := make(map[string]struct{})
1855         for conn := range t.conns {
1856                 ra := conn.conn.RemoteAddr()
1857                 if ra == nil {
1858                         // It's been closed and doesn't support RemoteAddr.
1859                         continue
1860                 }
1861                 peers[ra.String()] = struct{}{}
1862         }
1863         for addr := range t.halfOpen {
1864                 peers[addr] = struct{}{}
1865         }
1866         t.peers.Each(func(peer PeerInfo) {
1867                 peers[peer.Addr.String()] = struct{}{}
1868         })
1869         return len(peers)
1870 }
1871
1872 // Reconcile bytes transferred before connection was associated with a
1873 // torrent.
1874 func (t *Torrent) reconcileHandshakeStats(c *PeerConn) {
1875         if c._stats != (ConnStats{
1876                 // Handshakes should only increment these fields:
1877                 BytesWritten: c._stats.BytesWritten,
1878                 BytesRead:    c._stats.BytesRead,
1879         }) {
1880                 panic("bad stats")
1881         }
1882         c.postHandshakeStats(func(cs *ConnStats) {
1883                 cs.BytesRead.Add(c._stats.BytesRead.Int64())
1884                 cs.BytesWritten.Add(c._stats.BytesWritten.Int64())
1885         })
1886         c.reconciledHandshakeStats = true
1887 }
1888
1889 // Returns true if the connection is added.
1890 func (t *Torrent) addPeerConn(c *PeerConn) (err error) {
1891         defer func() {
1892                 if err == nil {
1893                         torrent.Add("added connections", 1)
1894                 }
1895         }()
1896         if t.closed.IsSet() {
1897                 return errors.New("torrent closed")
1898         }
1899         for c0 := range t.conns {
1900                 if c.PeerID != c0.PeerID {
1901                         continue
1902                 }
1903                 if !t.cl.config.DropDuplicatePeerIds {
1904                         continue
1905                 }
1906                 if c.hasPreferredNetworkOver(c0) {
1907                         c0.close()
1908                         t.deletePeerConn(c0)
1909                 } else {
1910                         return errors.New("existing connection preferred")
1911                 }
1912         }
1913         if len(t.conns) >= t.maxEstablishedConns {
1914                 c := t.worstBadConn()
1915                 if c == nil {
1916                         return errors.New("don't want conns")
1917                 }
1918                 c.close()
1919                 t.deletePeerConn(c)
1920         }
1921         if len(t.conns) >= t.maxEstablishedConns {
1922                 panic(len(t.conns))
1923         }
1924         t.conns[c] = struct{}{}
1925         if !t.cl.config.DisablePEX && !c.PeerExtensionBytes.SupportsExtended() {
1926                 t.pex.Add(c) // as no further extended handshake expected
1927         }
1928         return nil
1929 }
1930
1931 func (t *Torrent) wantConns() bool {
1932         if !t.networkingEnabled.Bool() {
1933                 return false
1934         }
1935         if t.closed.IsSet() {
1936                 return false
1937         }
1938         if !t.needData() && (!t.seeding() || !t.haveAnyPieces()) {
1939                 return false
1940         }
1941         return len(t.conns) < t.maxEstablishedConns || t.worstBadConn() != nil
1942 }
1943
1944 func (t *Torrent) SetMaxEstablishedConns(max int) (oldMax int) {
1945         t.cl.lock()
1946         defer t.cl.unlock()
1947         oldMax = t.maxEstablishedConns
1948         t.maxEstablishedConns = max
1949         wcs := worseConnSlice{
1950                 conns: t.appendConns(nil, func(*PeerConn) bool {
1951                         return true
1952                 }),
1953         }
1954         wcs.initKeys()
1955         heap.Init(&wcs)
1956         for len(t.conns) > t.maxEstablishedConns && wcs.Len() > 0 {
1957                 t.dropConnection(heap.Pop(&wcs).(*PeerConn))
1958         }
1959         t.openNewConns()
1960         return oldMax
1961 }
1962
1963 func (t *Torrent) pieceHashed(piece pieceIndex, passed bool, hashIoErr error) {
1964         t.logger.LazyLog(log.Debug, func() log.Msg {
1965                 return log.Fstr("hashed piece %d (passed=%t)", piece, passed)
1966         })
1967         p := t.piece(piece)
1968         p.numVerifies++
1969         t.cl.event.Broadcast()
1970         if t.closed.IsSet() {
1971                 return
1972         }
1973
1974         // Don't score the first time a piece is hashed, it could be an initial check.
1975         if p.storageCompletionOk {
1976                 if passed {
1977                         pieceHashedCorrect.Add(1)
1978                 } else {
1979                         log.Fmsg(
1980                                 "piece %d failed hash: %d connections contributed", piece, len(p.dirtiers),
1981                         ).AddValues(t, p).LogLevel(
1982
1983                                 log.Debug, t.logger)
1984
1985                         pieceHashedNotCorrect.Add(1)
1986                 }
1987         }
1988
1989         p.marking = true
1990         t.publishPieceChange(piece)
1991         defer func() {
1992                 p.marking = false
1993                 t.publishPieceChange(piece)
1994         }()
1995
1996         if passed {
1997                 if len(p.dirtiers) != 0 {
1998                         // Don't increment stats above connection-level for every involved connection.
1999                         t.allStats((*ConnStats).incrementPiecesDirtiedGood)
2000                 }
2001                 for c := range p.dirtiers {
2002                         c._stats.incrementPiecesDirtiedGood()
2003                 }
2004                 t.clearPieceTouchers(piece)
2005                 t.cl.unlock()
2006                 err := p.Storage().MarkComplete()
2007                 if err != nil {
2008                         t.logger.Printf("%T: error marking piece complete %d: %s", t.storage, piece, err)
2009                 }
2010                 t.cl.lock()
2011
2012                 if t.closed.IsSet() {
2013                         return
2014                 }
2015                 t.pendAllChunkSpecs(piece)
2016         } else {
2017                 if len(p.dirtiers) != 0 && p.allChunksDirty() && hashIoErr == nil {
2018                         // Peers contributed to all the data for this piece hash failure, and the failure was
2019                         // not due to errors in the storage (such as data being dropped in a cache).
2020
2021                         // Increment Torrent and above stats, and then specific connections.
2022                         t.allStats((*ConnStats).incrementPiecesDirtiedBad)
2023                         for c := range p.dirtiers {
2024                                 // Y u do dis peer?!
2025                                 c.stats().incrementPiecesDirtiedBad()
2026                         }
2027
2028                         bannableTouchers := make([]*Peer, 0, len(p.dirtiers))
2029                         for c := range p.dirtiers {
2030                                 if !c.trusted {
2031                                         bannableTouchers = append(bannableTouchers, c)
2032                                 }
2033                         }
2034                         t.clearPieceTouchers(piece)
2035                         slices.Sort(bannableTouchers, connLessTrusted)
2036
2037                         if t.cl.config.Debug {
2038                                 t.logger.Printf(
2039                                         "bannable conns by trust for piece %d: %v",
2040                                         piece,
2041                                         func() (ret []connectionTrust) {
2042                                                 for _, c := range bannableTouchers {
2043                                                         ret = append(ret, c.trust())
2044                                                 }
2045                                                 return
2046                                         }(),
2047                                 )
2048                         }
2049
2050                         if len(bannableTouchers) >= 1 {
2051                                 c := bannableTouchers[0]
2052                                 if len(bannableTouchers) != 1 {
2053                                         t.logger.Levelf(log.Warning, "would have banned %v for touching piece %v after failed piece check", c.remoteIp(), piece)
2054                                 } else {
2055                                         // Turns out it's still useful to ban peers like this because if there's only a
2056                                         // single peer for a piece, and we never progress that piece to completion, we
2057                                         // will never smart-ban them. Discovered in
2058                                         // https://github.com/anacrolix/torrent/issues/715.
2059                                         t.logger.Levelf(log.Warning, "banning %v for being sole dirtier of piece %v after failed piece check", c, piece)
2060                                         c.ban()
2061                                 }
2062                         }
2063                 }
2064                 t.onIncompletePiece(piece)
2065                 p.Storage().MarkNotComplete()
2066         }
2067         t.updatePieceCompletion(piece)
2068 }
2069
2070 func (t *Torrent) cancelRequestsForPiece(piece pieceIndex) {
2071         for ri := t.pieceRequestIndexOffset(piece); ri < t.pieceRequestIndexOffset(piece+1); ri++ {
2072                 t.cancelRequest(ri)
2073         }
2074 }
2075
2076 func (t *Torrent) onPieceCompleted(piece pieceIndex) {
2077         t.pendAllChunkSpecs(piece)
2078         t.cancelRequestsForPiece(piece)
2079         t.piece(piece).readerCond.Broadcast()
2080         for conn := range t.conns {
2081                 conn.have(piece)
2082                 t.maybeDropMutuallyCompletePeer(&conn.Peer)
2083         }
2084 }
2085
2086 // Called when a piece is found to be not complete.
2087 func (t *Torrent) onIncompletePiece(piece pieceIndex) {
2088         if t.pieceAllDirty(piece) {
2089                 t.pendAllChunkSpecs(piece)
2090         }
2091         if !t.wantPieceIndex(piece) {
2092                 // t.logger.Printf("piece %d incomplete and unwanted", piece)
2093                 return
2094         }
2095         // We could drop any connections that we told we have a piece that we
2096         // don't here. But there's a test failure, and it seems clients don't care
2097         // if you request pieces that you already claim to have. Pruning bad
2098         // connections might just remove any connections that aren't treating us
2099         // favourably anyway.
2100
2101         // for c := range t.conns {
2102         //      if c.sentHave(piece) {
2103         //              c.drop()
2104         //      }
2105         // }
2106         t.iterPeers(func(conn *Peer) {
2107                 if conn.peerHasPiece(piece) {
2108                         conn.updateRequests("piece incomplete")
2109                 }
2110         })
2111 }
2112
2113 func (t *Torrent) tryCreateMorePieceHashers() {
2114         for !t.closed.IsSet() && t.activePieceHashes < 2 && t.tryCreatePieceHasher() {
2115         }
2116 }
2117
2118 func (t *Torrent) tryCreatePieceHasher() bool {
2119         if t.storage == nil {
2120                 return false
2121         }
2122         pi, ok := t.getPieceToHash()
2123         if !ok {
2124                 return false
2125         }
2126         p := t.piece(pi)
2127         t.piecesQueuedForHash.Remove(bitmap.BitIndex(pi))
2128         p.hashing = true
2129         t.publishPieceChange(pi)
2130         t.updatePiecePriority(pi, "Torrent.tryCreatePieceHasher")
2131         t.storageLock.RLock()
2132         t.activePieceHashes++
2133         go t.pieceHasher(pi)
2134         return true
2135 }
2136
2137 func (t *Torrent) getPieceToHash() (ret pieceIndex, ok bool) {
2138         t.piecesQueuedForHash.IterTyped(func(i pieceIndex) bool {
2139                 if t.piece(i).hashing {
2140                         return true
2141                 }
2142                 ret = i
2143                 ok = true
2144                 return false
2145         })
2146         return
2147 }
2148
2149 func (t *Torrent) dropBannedPeers() {
2150         t.iterPeers(func(p *Peer) {
2151                 remoteIp := p.remoteIp()
2152                 if remoteIp == nil {
2153                         if p.bannableAddr.Ok() {
2154                                 log.Printf("can't get remote ip for peer %v", p)
2155                         }
2156                         return
2157                 }
2158                 netipAddr := netip.MustParseAddr(remoteIp.String())
2159                 if Some(netipAddr) != p.bannableAddr {
2160                         log.Printf(
2161                                 "peer remote ip does not match its bannable addr [peer=%v, remote ip=%v, bannable addr=%v]",
2162                                 p, remoteIp, p.bannableAddr)
2163                 }
2164                 if _, ok := t.cl.badPeerIPs[netipAddr]; ok {
2165                         // Should this be a close?
2166                         p.drop()
2167                         log.Printf("dropped %v for banned remote IP %v", p, netipAddr)
2168                 }
2169         })
2170 }
2171
2172 func (t *Torrent) pieceHasher(index pieceIndex) {
2173         p := t.piece(index)
2174         sum, failedPeers, copyErr := t.hashPiece(index)
2175         correct := sum == *p.hash
2176         switch copyErr {
2177         case nil, io.EOF:
2178         default:
2179                 log.Fmsg("piece %v (%s) hash failure copy error: %v", p, p.hash.HexString(), copyErr).Log(t.logger)
2180         }
2181         t.storageLock.RUnlock()
2182         t.cl.lock()
2183         defer t.cl.unlock()
2184         if correct {
2185                 for peer := range failedPeers {
2186                         t.cl.banPeerIP(peer.AsSlice())
2187                         log.Printf("smart banned %v for piece %v", peer, index)
2188                 }
2189                 t.dropBannedPeers()
2190                 for ri := t.pieceRequestIndexOffset(index); ri < t.pieceRequestIndexOffset(index+1); ri++ {
2191                         t.smartBanCache.ForgetBlock(ri)
2192                 }
2193         }
2194         p.hashing = false
2195         t.pieceHashed(index, correct, copyErr)
2196         t.updatePiecePriority(index, "Torrent.pieceHasher")
2197         t.activePieceHashes--
2198         t.tryCreateMorePieceHashers()
2199 }
2200
2201 // Return the connections that touched a piece, and clear the entries while doing it.
2202 func (t *Torrent) clearPieceTouchers(pi pieceIndex) {
2203         p := t.piece(pi)
2204         for c := range p.dirtiers {
2205                 delete(c.peerTouchedPieces, pi)
2206                 delete(p.dirtiers, c)
2207         }
2208 }
2209
2210 func (t *Torrent) peersAsSlice() (ret []*Peer) {
2211         t.iterPeers(func(p *Peer) {
2212                 ret = append(ret, p)
2213         })
2214         return
2215 }
2216
2217 func (t *Torrent) queuePieceCheck(pieceIndex pieceIndex) {
2218         piece := t.piece(pieceIndex)
2219         if piece.queuedForHash() {
2220                 return
2221         }
2222         t.piecesQueuedForHash.Add(bitmap.BitIndex(pieceIndex))
2223         t.publishPieceChange(pieceIndex)
2224         t.updatePiecePriority(pieceIndex, "Torrent.queuePieceCheck")
2225         t.tryCreateMorePieceHashers()
2226 }
2227
2228 // Forces all the pieces to be re-hashed. See also Piece.VerifyData. This should not be called
2229 // before the Info is available.
2230 func (t *Torrent) VerifyData() {
2231         for i := pieceIndex(0); i < t.NumPieces(); i++ {
2232                 t.Piece(i).VerifyData()
2233         }
2234 }
2235
2236 // Start the process of connecting to the given peer for the given torrent if appropriate.
2237 func (t *Torrent) initiateConn(peer PeerInfo) {
2238         if peer.Id == t.cl.peerID {
2239                 return
2240         }
2241         if t.cl.badPeerAddr(peer.Addr) && !peer.Trusted {
2242                 return
2243         }
2244         addr := peer.Addr
2245         if t.addrActive(addr.String()) {
2246                 return
2247         }
2248         t.cl.numHalfOpen++
2249         t.halfOpen[addr.String()] = peer
2250         go t.cl.outgoingConnection(t, addr, peer.Source, peer.Trusted)
2251 }
2252
2253 // Adds a trusted, pending peer for each of the given Client's addresses. Typically used in tests to
2254 // quickly make one Client visible to the Torrent of another Client.
2255 func (t *Torrent) AddClientPeer(cl *Client) int {
2256         return t.AddPeers(func() (ps []PeerInfo) {
2257                 for _, la := range cl.ListenAddrs() {
2258                         ps = append(ps, PeerInfo{
2259                                 Addr:    la,
2260                                 Trusted: true,
2261                         })
2262                 }
2263                 return
2264         }())
2265 }
2266
2267 // All stats that include this Torrent. Useful when we want to increment ConnStats but not for every
2268 // connection.
2269 func (t *Torrent) allStats(f func(*ConnStats)) {
2270         f(&t.stats)
2271         f(&t.cl.stats)
2272 }
2273
2274 func (t *Torrent) hashingPiece(i pieceIndex) bool {
2275         return t.pieces[i].hashing
2276 }
2277
2278 func (t *Torrent) pieceQueuedForHash(i pieceIndex) bool {
2279         return t.piecesQueuedForHash.Get(bitmap.BitIndex(i))
2280 }
2281
2282 func (t *Torrent) dialTimeout() time.Duration {
2283         return reducedDialTimeout(t.cl.config.MinDialTimeout, t.cl.config.NominalDialTimeout, t.cl.config.HalfOpenConnsPerTorrent, t.peers.Len())
2284 }
2285
2286 func (t *Torrent) piece(i int) *Piece {
2287         return &t.pieces[i]
2288 }
2289
2290 func (t *Torrent) onWriteChunkErr(err error) {
2291         if t.userOnWriteChunkErr != nil {
2292                 go t.userOnWriteChunkErr(err)
2293                 return
2294         }
2295         t.logger.WithDefaultLevel(log.Critical).Printf("default chunk write error handler: disabling data download")
2296         t.disallowDataDownloadLocked()
2297 }
2298
2299 func (t *Torrent) DisallowDataDownload() {
2300         t.disallowDataDownloadLocked()
2301 }
2302
2303 func (t *Torrent) disallowDataDownloadLocked() {
2304         t.dataDownloadDisallowed.Set()
2305 }
2306
2307 func (t *Torrent) AllowDataDownload() {
2308         t.dataDownloadDisallowed.Clear()
2309 }
2310
2311 // Enables uploading data, if it was disabled.
2312 func (t *Torrent) AllowDataUpload() {
2313         t.cl.lock()
2314         defer t.cl.unlock()
2315         t.dataUploadDisallowed = false
2316         for c := range t.conns {
2317                 c.updateRequests("allow data upload")
2318         }
2319 }
2320
2321 // Disables uploading data, if it was enabled.
2322 func (t *Torrent) DisallowDataUpload() {
2323         t.cl.lock()
2324         defer t.cl.unlock()
2325         t.dataUploadDisallowed = true
2326         for c := range t.conns {
2327                 // TODO: This doesn't look right. Shouldn't we tickle writers to choke peers or something instead?
2328                 c.updateRequests("disallow data upload")
2329         }
2330 }
2331
2332 // Sets a handler that is called if there's an error writing a chunk to local storage. By default,
2333 // or if nil, a critical message is logged, and data download is disabled.
2334 func (t *Torrent) SetOnWriteChunkError(f func(error)) {
2335         t.cl.lock()
2336         defer t.cl.unlock()
2337         t.userOnWriteChunkErr = f
2338 }
2339
2340 func (t *Torrent) iterPeers(f func(p *Peer)) {
2341         for pc := range t.conns {
2342                 f(&pc.Peer)
2343         }
2344         for _, ws := range t.webSeeds {
2345                 f(ws)
2346         }
2347 }
2348
2349 func (t *Torrent) callbacks() *Callbacks {
2350         return &t.cl.config.Callbacks
2351 }
2352
2353 type AddWebseedsOpt func() *AddWebseedOpts
2354
2355 type AddWebseedOpts struct {
2356         // Custom encoder for webseed URLs
2357         // Leave nil to use the default (url.QueryEscape)
2358         PathEscaper webseed.PathEscaper
2359 }
2360
2361
2362 // Add web seeds to the torrent.
2363 // If opt is not nil, only the first one is used.
2364 func (t *Torrent) AddWebSeeds(urls []string, opt ...AddWebseedsOpt) {
2365         t.cl.lock()
2366         defer t.cl.unlock()
2367         for _, u := range urls {
2368                 if opt == nil {
2369                         t.addWebSeed(u, nil)
2370                 } else {
2371                         t.addWebSeed(u, opt[0]().PathEscaper)
2372                 }
2373         }
2374 }
2375
2376 func (t *Torrent) addWebSeed(url string, pathEscaper webseed.PathEscaper) {
2377         if t.cl.config.DisableWebseeds {
2378                 return
2379         }
2380         if _, ok := t.webSeeds[url]; ok {
2381                 return
2382         }
2383         // I don't think Go http supports pipelining requests. However, we can have more ready to go
2384         // right away. This value should be some multiple of the number of connections to a host. I
2385         // would expect that double maxRequests plus a bit would be appropriate. This value is based on
2386         // downloading Sintel (08ada5a7a6183aae1e09d831df6748d566095a10) from
2387         // "https://webtorrent.io/torrents/".
2388         const maxRequests = 16
2389         ws := webseedPeer{
2390                 peer: Peer{
2391                         t:                        t,
2392                         outgoing:                 true,
2393                         Network:                  "http",
2394                         reconciledHandshakeStats: true,
2395                         // This should affect how often we have to recompute requests for this peer. Note that
2396                         // because we can request more than 1 thing at a time over HTTP, we will hit the low
2397                         // requests mark more often, so recomputation is probably sooner than with regular peer
2398                         // conns. ~4x maxRequests would be about right.
2399                         PeerMaxRequests: 128,
2400                         // TODO: Set ban prefix?
2401                         RemoteAddr: remoteAddrFromUrl(url),
2402                         callbacks:  t.callbacks(),
2403                 },
2404                 client: webseed.Client{
2405                         HttpClient: t.cl.httpClient,
2406                         Url:        url,
2407                         ResponseBodyWrapper: func(r io.Reader) io.Reader {
2408                                 return &rateLimitedReader{
2409                                         l: t.cl.config.DownloadRateLimiter,
2410                                         r: r,
2411                                 }
2412                         },
2413                         PathEscaper: pathEscaper,
2414                 },
2415                 activeRequests: make(map[Request]webseed.Request, maxRequests),
2416                 maxRequests:    maxRequests,
2417         }
2418         ws.peer.initUpdateRequestsTimer()
2419         ws.requesterCond.L = t.cl.locker()
2420         for i := 0; i < maxRequests; i += 1 {
2421                 go ws.requester(i)
2422         }
2423         for _, f := range t.callbacks().NewPeer {
2424                 f(&ws.peer)
2425         }
2426         ws.peer.logger = t.logger.WithContextValue(&ws)
2427         ws.peer.peerImpl = &ws
2428         if t.haveInfo() {
2429                 ws.onGotInfo(t.info)
2430         }
2431         t.webSeeds[url] = &ws.peer
2432 }
2433
2434 func (t *Torrent) peerIsActive(p *Peer) (active bool) {
2435         t.iterPeers(func(p1 *Peer) {
2436                 if p1 == p {
2437                         active = true
2438                 }
2439         })
2440         return
2441 }
2442
2443 func (t *Torrent) requestIndexToRequest(ri RequestIndex) Request {
2444         index := ri / t.chunksPerRegularPiece()
2445         return Request{
2446                 pp.Integer(index),
2447                 t.piece(int(index)).chunkIndexSpec(ri % t.chunksPerRegularPiece()),
2448         }
2449 }
2450
2451 func (t *Torrent) requestIndexFromRequest(r Request) RequestIndex {
2452         return t.pieceRequestIndexOffset(pieceIndex(r.Index)) + uint32(r.Begin/t.chunkSize)
2453 }
2454
2455 func (t *Torrent) pieceRequestIndexOffset(piece pieceIndex) RequestIndex {
2456         return RequestIndex(piece) * t.chunksPerRegularPiece()
2457 }
2458
2459 func (t *Torrent) updateComplete() {
2460         t.Complete.SetBool(t.haveAllPieces())
2461 }
2462
2463 func (t *Torrent) cancelRequest(r RequestIndex) *Peer {
2464         p := t.pendingRequests[r]
2465         if p != nil {
2466                 p.cancel(r)
2467         }
2468         delete(t.pendingRequests, r)
2469         return p
2470 }
2471
2472 func (t *Torrent) requestingPeer(r RequestIndex) *Peer {
2473         return t.pendingRequests[r]
2474 }
2475
2476 func (t *Torrent) addConnWithAllPieces(p *Peer) {
2477         if t.connsWithAllPieces == nil {
2478                 t.connsWithAllPieces = make(map[*Peer]struct{}, t.maxEstablishedConns)
2479         }
2480         t.connsWithAllPieces[p] = struct{}{}
2481 }
2482
2483 func (t *Torrent) deleteConnWithAllPieces(p *Peer) bool {
2484         _, ok := t.connsWithAllPieces[p]
2485         delete(t.connsWithAllPieces, p)
2486         return ok
2487 }
2488
2489 func (t *Torrent) numActivePeers() int {
2490         return len(t.conns) + len(t.webSeeds)
2491 }
2492
2493 func (t *Torrent) hasStorageCap() bool {
2494         f := t.storage.Capacity
2495         if f == nil {
2496                 return false
2497         }
2498         _, ok := (*f)()
2499         return ok
2500 }