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