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