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