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