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