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