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