]> Sergey Matveev's repositories - btrtrc.git/blob - torrent.go
Add a comment about not discarding in webseed OK response bodies
[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/google/go-cmp/cmp"
32         "github.com/pion/datachannel"
33
34         "github.com/anacrolix/torrent/bencode"
35         "github.com/anacrolix/torrent/common"
36         "github.com/anacrolix/torrent/metainfo"
37         pp "github.com/anacrolix/torrent/peer_protocol"
38         "github.com/anacrolix/torrent/segments"
39         "github.com/anacrolix/torrent/storage"
40         "github.com/anacrolix/torrent/tracker"
41         "github.com/anacrolix/torrent/webseed"
42         "github.com/anacrolix/torrent/webtorrent"
43 )
44
45 // Maintains state of torrent within a Client. Many methods should not be called before the info is
46 // available, see .Info and .GotInfo.
47 type Torrent struct {
48         // Torrent-level aggregate statistics. First in struct to ensure 64-bit
49         // alignment. See #262.
50         stats  ConnStats
51         cl     *Client
52         logger log.Logger
53
54         networkingEnabled      chansync.Flag
55         dataDownloadDisallowed chansync.Flag
56         dataUploadDisallowed   bool
57         userOnWriteChunkErr    func(error)
58
59         closed   chansync.SetOnce
60         infoHash metainfo.Hash
61         pieces   []Piece
62         // Values are the piece indices that changed.
63         pieceStateChanges *pubsub.PubSub
64         // The size of chunks to request from peers over the wire. This is
65         // normally 16KiB by convention these days.
66         chunkSize pp.Integer
67         chunkPool sync.Pool
68         // Total length of the torrent in bytes. Stored because it's not O(1) to
69         // get this from the info dict.
70         length *int64
71
72         // The storage to open when the info dict becomes available.
73         storageOpener *storage.Client
74         // Storage for torrent data.
75         storage *storage.Torrent
76         // Read-locked for using storage, and write-locked for Closing.
77         storageLock sync.RWMutex
78
79         // TODO: Only announce stuff is used?
80         metainfo metainfo.MetaInfo
81
82         // The info dict. nil if we don't have it (yet).
83         info      *metainfo.Info
84         fileIndex segments.Index
85         files     *[]*File
86
87         webSeeds map[string]*Peer
88
89         // Active peer connections, running message stream loops. TODO: Make this
90         // open (not-closed) connections only.
91         conns               map[*PeerConn]struct{}
92         maxEstablishedConns int
93         // Set of addrs to which we're attempting to connect. Connections are
94         // half-open until all handshakes are completed.
95         halfOpen map[string]PeerInfo
96
97         // Reserve of peers to connect to. A peer can be both here and in the
98         // active connections if were told about the peer after connecting with
99         // them. That encourages us to reconnect to peers that are well known in
100         // the swarm.
101         peers prioritizedPeers
102         // Whether we want to know to know more peers.
103         wantPeersEvent missinggo.Event
104         // An announcer for each tracker URL.
105         trackerAnnouncers map[string]torrentTrackerAnnouncer
106         // How many times we've initiated a DHT announce. TODO: Move into stats.
107         numDHTAnnounces int
108
109         // Name used if the info name isn't available. Should be cleared when the
110         // Info does become available.
111         nameMu      sync.RWMutex
112         displayName string
113
114         // The bencoded bytes of the info dict. This is actively manipulated if
115         // the info bytes aren't initially available, and we try to fetch them
116         // from peers.
117         metadataBytes []byte
118         // Each element corresponds to the 16KiB metadata pieces. If true, we have
119         // received that piece.
120         metadataCompletedChunks []bool
121         metadataChanged         sync.Cond
122
123         // Closed when .Info is obtained.
124         gotMetainfoC chan struct{}
125
126         readers                map[*reader]struct{}
127         _readerNowPieces       bitmap.Bitmap
128         _readerReadaheadPieces bitmap.Bitmap
129
130         // A cache of pieces we need to get. Calculated from various piece and
131         // file priorities and completion states elsewhere.
132         _pendingPieces roaring.Bitmap
133         // A cache of completed piece indices.
134         _completedPieces roaring.Bitmap
135         // Pieces that need to be hashed.
136         piecesQueuedForHash       bitmap.Bitmap
137         activePieceHashes         int
138         initialPieceCheckDisabled bool
139
140         // Count of each request across active connections.
141         pendingRequests pendingRequests
142         // Chunks we've written to since the corresponding piece was last checked.
143         dirtyChunks roaring.Bitmap
144
145         pex pexState
146
147         // Is On when all pieces are complete.
148         Complete chansync.Flag
149 }
150
151 func (t *Torrent) pieceAvailabilityFromPeers(i pieceIndex) (count int) {
152         t.iterPeers(func(peer *Peer) {
153                 if peer.peerHasPiece(i) {
154                         count++
155                 }
156         })
157         return
158 }
159
160 func (t *Torrent) decPieceAvailability(i pieceIndex) {
161         if !t.haveInfo() {
162                 return
163         }
164         p := t.piece(i)
165         if p.availability <= 0 {
166                 panic(p.availability)
167         }
168         p.availability--
169 }
170
171 func (t *Torrent) incPieceAvailability(i pieceIndex) {
172         // If we don't the info, this should be reconciled when we do.
173         if t.haveInfo() {
174                 p := t.piece(i)
175                 p.availability++
176         }
177 }
178
179 func (t *Torrent) readerNowPieces() bitmap.Bitmap {
180         return t._readerNowPieces
181 }
182
183 func (t *Torrent) readerReadaheadPieces() bitmap.Bitmap {
184         return t._readerReadaheadPieces
185 }
186
187 func (t *Torrent) ignorePieceForRequests(i pieceIndex) bool {
188         return !t.wantPieceIndex(i)
189 }
190
191 // Returns a channel that is closed when the Torrent is closed.
192 func (t *Torrent) Closed() events.Done {
193         return t.closed.Done()
194 }
195
196 // KnownSwarm returns the known subset of the peers in the Torrent's swarm, including active,
197 // pending, and half-open peers.
198 func (t *Torrent) KnownSwarm() (ks []PeerInfo) {
199         // Add pending peers to the list
200         t.peers.Each(func(peer PeerInfo) {
201                 ks = append(ks, peer)
202         })
203
204         // Add half-open peers to the list
205         for _, peer := range t.halfOpen {
206                 ks = append(ks, peer)
207         }
208
209         // Add active peers to the list
210         for conn := range t.conns {
211                 ks = append(ks, PeerInfo{
212                         Id:     conn.PeerID,
213                         Addr:   conn.RemoteAddr,
214                         Source: conn.Discovery,
215                         // > If the connection is encrypted, that's certainly enough to set SupportsEncryption.
216                         // > But if we're not connected to them with an encrypted connection, I couldn't say
217                         // > what's appropriate. We can carry forward the SupportsEncryption value as we
218                         // > received it from trackers/DHT/PEX, or just use the encryption state for the
219                         // > connection. It's probably easiest to do the latter for now.
220                         // https://github.com/anacrolix/torrent/pull/188
221                         SupportsEncryption: conn.headerEncrypted,
222                 })
223         }
224
225         return
226 }
227
228 func (t *Torrent) setChunkSize(size pp.Integer) {
229         t.chunkSize = size
230         t.chunkPool = sync.Pool{
231                 New: func() interface{} {
232                         b := make([]byte, size)
233                         return &b
234                 },
235         }
236 }
237
238 func (t *Torrent) pieceComplete(piece pieceIndex) bool {
239         return t._completedPieces.Contains(bitmap.BitIndex(piece))
240 }
241
242 func (t *Torrent) pieceCompleteUncached(piece pieceIndex) storage.Completion {
243         return t.pieces[piece].Storage().Completion()
244 }
245
246 // There's a connection to that address already.
247 func (t *Torrent) addrActive(addr string) bool {
248         if _, ok := t.halfOpen[addr]; ok {
249                 return true
250         }
251         for c := range t.conns {
252                 ra := c.RemoteAddr
253                 if ra.String() == addr {
254                         return true
255                 }
256         }
257         return false
258 }
259
260 func (t *Torrent) appendUnclosedConns(ret []*PeerConn) []*PeerConn {
261         for c := range t.conns {
262                 if !c.closed.IsSet() {
263                         ret = append(ret, c)
264                 }
265         }
266         return ret
267 }
268
269 func (t *Torrent) addPeer(p PeerInfo) (added bool) {
270         cl := t.cl
271         torrent.Add(fmt.Sprintf("peers added by source %q", p.Source), 1)
272         if t.closed.IsSet() {
273                 return false
274         }
275         if ipAddr, ok := tryIpPortFromNetAddr(p.Addr); ok {
276                 if cl.badPeerIPPort(ipAddr.IP, ipAddr.Port) {
277                         torrent.Add("peers not added because of bad addr", 1)
278                         // cl.logger.Printf("peers not added because of bad addr: %v", p)
279                         return false
280                 }
281         }
282         if replaced, ok := t.peers.AddReturningReplacedPeer(p); ok {
283                 torrent.Add("peers replaced", 1)
284                 if !replaced.equal(p) {
285                         t.logger.WithDefaultLevel(log.Debug).Printf("added %v replacing %v", p, replaced)
286                         added = true
287                 }
288         } else {
289                 added = true
290         }
291         t.openNewConns()
292         for t.peers.Len() > cl.config.TorrentPeersHighWater {
293                 _, ok := t.peers.DeleteMin()
294                 if ok {
295                         torrent.Add("excess reserve peers discarded", 1)
296                 }
297         }
298         return
299 }
300
301 func (t *Torrent) invalidateMetadata() {
302         for i := 0; i < len(t.metadataCompletedChunks); i++ {
303                 t.metadataCompletedChunks[i] = false
304         }
305         t.nameMu.Lock()
306         t.gotMetainfoC = make(chan struct{})
307         t.info = nil
308         t.nameMu.Unlock()
309 }
310
311 func (t *Torrent) saveMetadataPiece(index int, data []byte) {
312         if t.haveInfo() {
313                 return
314         }
315         if index >= len(t.metadataCompletedChunks) {
316                 t.logger.Printf("%s: ignoring metadata piece %d", t, index)
317                 return
318         }
319         copy(t.metadataBytes[(1<<14)*index:], data)
320         t.metadataCompletedChunks[index] = true
321 }
322
323 func (t *Torrent) metadataPieceCount() int {
324         return (len(t.metadataBytes) + (1 << 14) - 1) / (1 << 14)
325 }
326
327 func (t *Torrent) haveMetadataPiece(piece int) bool {
328         if t.haveInfo() {
329                 return (1<<14)*piece < len(t.metadataBytes)
330         } else {
331                 return piece < len(t.metadataCompletedChunks) && t.metadataCompletedChunks[piece]
332         }
333 }
334
335 func (t *Torrent) metadataSize() int {
336         return len(t.metadataBytes)
337 }
338
339 func infoPieceHashes(info *metainfo.Info) (ret [][]byte) {
340         for i := 0; i < len(info.Pieces); i += sha1.Size {
341                 ret = append(ret, info.Pieces[i:i+sha1.Size])
342         }
343         return
344 }
345
346 func (t *Torrent) makePieces() {
347         hashes := infoPieceHashes(t.info)
348         t.pieces = make([]Piece, len(hashes))
349         for i, hash := range hashes {
350                 piece := &t.pieces[i]
351                 piece.t = t
352                 piece.index = pieceIndex(i)
353                 piece.noPendingWrites.L = &piece.pendingWritesMutex
354                 piece.hash = (*metainfo.Hash)(unsafe.Pointer(&hash[0]))
355                 files := *t.files
356                 beginFile := pieceFirstFileIndex(piece.torrentBeginOffset(), files)
357                 endFile := pieceEndFileIndex(piece.torrentEndOffset(), files)
358                 piece.files = files[beginFile:endFile]
359                 piece.undirtiedChunksIter = undirtiedChunksIter{
360                         TorrentDirtyChunks: &t.dirtyChunks,
361                         StartRequestIndex:  piece.requestIndexOffset(),
362                         EndRequestIndex:    piece.requestIndexOffset() + piece.numChunks(),
363                 }
364         }
365 }
366
367 // Returns the index of the first file containing the piece. files must be
368 // ordered by offset.
369 func pieceFirstFileIndex(pieceOffset int64, files []*File) int {
370         for i, f := range files {
371                 if f.offset+f.length > pieceOffset {
372                         return i
373                 }
374         }
375         return 0
376 }
377
378 // Returns the index after the last file containing the piece. files must be
379 // ordered by offset.
380 func pieceEndFileIndex(pieceEndOffset int64, files []*File) int {
381         for i, f := range files {
382                 if f.offset+f.length >= pieceEndOffset {
383                         return i + 1
384                 }
385         }
386         return 0
387 }
388
389 func (t *Torrent) cacheLength() {
390         var l int64
391         for _, f := range t.info.UpvertedFiles() {
392                 l += f.Length
393         }
394         t.length = &l
395 }
396
397 // TODO: This shouldn't fail for storage reasons. Instead we should handle storage failure
398 // separately.
399 func (t *Torrent) setInfo(info *metainfo.Info) error {
400         if err := validateInfo(info); err != nil {
401                 return fmt.Errorf("bad info: %s", err)
402         }
403         if t.storageOpener != nil {
404                 var err error
405                 t.storage, err = t.storageOpener.OpenTorrent(info, t.infoHash)
406                 if err != nil {
407                         return fmt.Errorf("error opening torrent storage: %s", err)
408                 }
409         }
410         t.nameMu.Lock()
411         t.info = info
412         t.nameMu.Unlock()
413         t.updateComplete()
414         t.fileIndex = segments.NewIndex(common.LengthIterFromUpvertedFiles(info.UpvertedFiles()))
415         t.displayName = "" // Save a few bytes lol.
416         t.initFiles()
417         t.cacheLength()
418         t.makePieces()
419         return nil
420 }
421
422 // This seems to be all the follow-up tasks after info is set, that can't fail.
423 func (t *Torrent) onSetInfo() {
424         for i := range t.pieces {
425                 p := &t.pieces[i]
426                 // Need to add availability before updating piece completion, as that may result in conns
427                 // being dropped.
428                 if p.availability != 0 {
429                         panic(p.availability)
430                 }
431                 p.availability = int64(t.pieceAvailabilityFromPeers(i))
432                 t.updatePieceCompletion(pieceIndex(i))
433                 if !t.initialPieceCheckDisabled && !p.storageCompletionOk {
434                         // t.logger.Printf("piece %s completion unknown, queueing check", p)
435                         t.queuePieceCheck(pieceIndex(i))
436                 }
437         }
438         t.cl.event.Broadcast()
439         close(t.gotMetainfoC)
440         t.updateWantPeersEvent()
441         t.pendingRequests.Init(t.numRequests())
442         t.tryCreateMorePieceHashers()
443         t.iterPeers(func(p *Peer) {
444                 p.onGotInfo(t.info)
445                 p.updateRequests("onSetInfo")
446         })
447 }
448
449 // Called when metadata for a torrent becomes available.
450 func (t *Torrent) setInfoBytesLocked(b []byte) error {
451         if metainfo.HashBytes(b) != t.infoHash {
452                 return errors.New("info bytes have wrong hash")
453         }
454         var info metainfo.Info
455         if err := bencode.Unmarshal(b, &info); err != nil {
456                 return fmt.Errorf("error unmarshalling info bytes: %s", err)
457         }
458         t.metadataBytes = b
459         t.metadataCompletedChunks = nil
460         if t.info != nil {
461                 return nil
462         }
463         if err := t.setInfo(&info); err != nil {
464                 return err
465         }
466         t.onSetInfo()
467         return nil
468 }
469
470 func (t *Torrent) haveAllMetadataPieces() bool {
471         if t.haveInfo() {
472                 return true
473         }
474         if t.metadataCompletedChunks == nil {
475                 return false
476         }
477         for _, have := range t.metadataCompletedChunks {
478                 if !have {
479                         return false
480                 }
481         }
482         return true
483 }
484
485 // TODO: Propagate errors to disconnect peer.
486 func (t *Torrent) setMetadataSize(size int) (err error) {
487         if t.haveInfo() {
488                 // We already know the correct metadata size.
489                 return
490         }
491         if uint32(size) > maxMetadataSize {
492                 return errors.New("bad size")
493         }
494         if len(t.metadataBytes) == size {
495                 return
496         }
497         t.metadataBytes = make([]byte, size)
498         t.metadataCompletedChunks = make([]bool, (size+(1<<14)-1)/(1<<14))
499         t.metadataChanged.Broadcast()
500         for c := range t.conns {
501                 c.requestPendingMetadata()
502         }
503         return
504 }
505
506 // The current working name for the torrent. Either the name in the info dict,
507 // or a display name given such as by the dn value in a magnet link, or "".
508 func (t *Torrent) name() string {
509         t.nameMu.RLock()
510         defer t.nameMu.RUnlock()
511         if t.haveInfo() {
512                 return t.info.Name
513         }
514         if t.displayName != "" {
515                 return t.displayName
516         }
517         return "infohash:" + t.infoHash.HexString()
518 }
519
520 func (t *Torrent) pieceState(index pieceIndex) (ret PieceState) {
521         p := &t.pieces[index]
522         ret.Priority = t.piecePriority(index)
523         ret.Completion = p.completion()
524         ret.QueuedForHash = p.queuedForHash()
525         ret.Hashing = p.hashing
526         ret.Checking = ret.QueuedForHash || ret.Hashing
527         ret.Marking = p.marking
528         if !ret.Complete && t.piecePartiallyDownloaded(index) {
529                 ret.Partial = true
530         }
531         return
532 }
533
534 func (t *Torrent) metadataPieceSize(piece int) int {
535         return metadataPieceSize(len(t.metadataBytes), piece)
536 }
537
538 func (t *Torrent) newMetadataExtensionMessage(c *PeerConn, msgType pp.ExtendedMetadataRequestMsgType, piece int, data []byte) pp.Message {
539         return pp.Message{
540                 Type:       pp.Extended,
541                 ExtendedID: c.PeerExtensionIDs[pp.ExtensionNameMetadata],
542                 ExtendedPayload: append(bencode.MustMarshal(pp.ExtendedMetadataRequestMsg{
543                         Piece:     piece,
544                         TotalSize: len(t.metadataBytes),
545                         Type:      msgType,
546                 }), data...),
547         }
548 }
549
550 type pieceAvailabilityRun struct {
551         count        pieceIndex
552         availability int64
553 }
554
555 func (me pieceAvailabilityRun) String() string {
556         return fmt.Sprintf("%v(%v)", me.count, me.availability)
557 }
558
559 func (t *Torrent) pieceAvailabilityRuns() (ret []pieceAvailabilityRun) {
560         rle := missinggo.NewRunLengthEncoder(func(el interface{}, count uint64) {
561                 ret = append(ret, pieceAvailabilityRun{availability: el.(int64), count: int(count)})
562         })
563         for i := range t.pieces {
564                 rle.Append(t.pieces[i].availability, 1)
565         }
566         rle.Flush()
567         return
568 }
569
570 func (t *Torrent) pieceStateRuns() (ret PieceStateRuns) {
571         rle := missinggo.NewRunLengthEncoder(func(el interface{}, count uint64) {
572                 ret = append(ret, PieceStateRun{
573                         PieceState: el.(PieceState),
574                         Length:     int(count),
575                 })
576         })
577         for index := range t.pieces {
578                 rle.Append(t.pieceState(pieceIndex(index)), 1)
579         }
580         rle.Flush()
581         return
582 }
583
584 // Produces a small string representing a PieceStateRun.
585 func (psr PieceStateRun) String() (ret string) {
586         ret = fmt.Sprintf("%d", psr.Length)
587         ret += func() string {
588                 switch psr.Priority {
589                 case PiecePriorityNext:
590                         return "N"
591                 case PiecePriorityNormal:
592                         return "."
593                 case PiecePriorityReadahead:
594                         return "R"
595                 case PiecePriorityNow:
596                         return "!"
597                 case PiecePriorityHigh:
598                         return "H"
599                 default:
600                         return ""
601                 }
602         }()
603         if psr.Hashing {
604                 ret += "H"
605         }
606         if psr.QueuedForHash {
607                 ret += "Q"
608         }
609         if psr.Marking {
610                 ret += "M"
611         }
612         if psr.Partial {
613                 ret += "P"
614         }
615         if psr.Complete {
616                 ret += "C"
617         }
618         if !psr.Ok {
619                 ret += "?"
620         }
621         return
622 }
623
624 func (t *Torrent) writeStatus(w io.Writer) {
625         fmt.Fprintf(w, "Infohash: %s\n", t.infoHash.HexString())
626         fmt.Fprintf(w, "Metadata length: %d\n", t.metadataSize())
627         if !t.haveInfo() {
628                 fmt.Fprintf(w, "Metadata have: ")
629                 for _, h := range t.metadataCompletedChunks {
630                         fmt.Fprintf(w, "%c", func() rune {
631                                 if h {
632                                         return 'H'
633                                 } else {
634                                         return '.'
635                                 }
636                         }())
637                 }
638                 fmt.Fprintln(w)
639         }
640         fmt.Fprintf(w, "Piece length: %s\n",
641                 func() string {
642                         if t.haveInfo() {
643                                 return fmt.Sprintf("%v (%v chunks)",
644                                         t.usualPieceSize(),
645                                         float64(t.usualPieceSize())/float64(t.chunkSize))
646                         } else {
647                                 return "no info"
648                         }
649                 }(),
650         )
651         if t.info != nil {
652                 fmt.Fprintf(w, "Num Pieces: %d (%d completed)\n", t.numPieces(), t.numPiecesCompleted())
653                 fmt.Fprintf(w, "Piece States: %s\n", t.pieceStateRuns())
654                 fmt.Fprintf(w, "Piece availability: %v\n", strings.Join(func() (ret []string) {
655                         for _, run := range t.pieceAvailabilityRuns() {
656                                 ret = append(ret, run.String())
657                         }
658                         return
659                 }(), " "))
660         }
661         fmt.Fprintf(w, "Reader Pieces:")
662         t.forReaderOffsetPieces(func(begin, end pieceIndex) (again bool) {
663                 fmt.Fprintf(w, " %d:%d", begin, end)
664                 return true
665         })
666         fmt.Fprintln(w)
667
668         fmt.Fprintf(w, "Enabled trackers:\n")
669         func() {
670                 tw := tabwriter.NewWriter(w, 0, 0, 2, ' ', 0)
671                 fmt.Fprintf(tw, "    URL\tExtra\n")
672                 for _, ta := range slices.Sort(slices.FromMapElems(t.trackerAnnouncers), func(l, r torrentTrackerAnnouncer) bool {
673                         lu := l.URL()
674                         ru := r.URL()
675                         var luns, runs url.URL = *lu, *ru
676                         luns.Scheme = ""
677                         runs.Scheme = ""
678                         var ml missinggo.MultiLess
679                         ml.StrictNext(luns.String() == runs.String(), luns.String() < runs.String())
680                         ml.StrictNext(lu.String() == ru.String(), lu.String() < ru.String())
681                         return ml.Less()
682                 }).([]torrentTrackerAnnouncer) {
683                         fmt.Fprintf(tw, "    %q\t%v\n", ta.URL(), ta.statusLine())
684                 }
685                 tw.Flush()
686         }()
687
688         fmt.Fprintf(w, "DHT Announces: %d\n", t.numDHTAnnounces)
689
690         spew.NewDefaultConfig()
691         spew.Fdump(w, t.statsLocked())
692
693         peers := t.peersAsSlice()
694         sort.Slice(peers, func(_i, _j int) bool {
695                 i := peers[_i]
696                 j := peers[_j]
697                 if less, ok := multiless.New().EagerSameLess(
698                         i.downloadRate() == j.downloadRate(), i.downloadRate() < j.downloadRate(),
699                 ).LessOk(); ok {
700                         return less
701                 }
702                 return worseConn(i, j)
703         })
704         for i, c := range peers {
705                 fmt.Fprintf(w, "%2d. ", i+1)
706                 c.writeStatus(w, t)
707         }
708 }
709
710 func (t *Torrent) haveInfo() bool {
711         return t.info != nil
712 }
713
714 // Returns a run-time generated MetaInfo that includes the info bytes and
715 // announce-list as currently known to the client.
716 func (t *Torrent) newMetaInfo() metainfo.MetaInfo {
717         return metainfo.MetaInfo{
718                 CreationDate: time.Now().Unix(),
719                 Comment:      "dynamic metainfo from client",
720                 CreatedBy:    "go.torrent",
721                 AnnounceList: t.metainfo.UpvertedAnnounceList().Clone(),
722                 InfoBytes: func() []byte {
723                         if t.haveInfo() {
724                                 return t.metadataBytes
725                         } else {
726                                 return nil
727                         }
728                 }(),
729                 UrlList: func() []string {
730                         ret := make([]string, 0, len(t.webSeeds))
731                         for url := range t.webSeeds {
732                                 ret = append(ret, url)
733                         }
734                         return ret
735                 }(),
736         }
737 }
738
739 // Get bytes left
740 func (t *Torrent) BytesMissing() (n int64) {
741         t.cl.rLock()
742         n = t.bytesMissingLocked()
743         t.cl.rUnlock()
744         return
745 }
746
747 func (t *Torrent) bytesMissingLocked() int64 {
748         return t.bytesLeft()
749 }
750
751 func iterFlipped(b *roaring.Bitmap, end uint64, cb func(uint32) bool) {
752         roaring.Flip(b, 0, end).Iterate(cb)
753 }
754
755 func (t *Torrent) bytesLeft() (left int64) {
756         iterFlipped(&t._completedPieces, uint64(t.numPieces()), func(x uint32) bool {
757                 p := t.piece(pieceIndex(x))
758                 left += int64(p.length() - p.numDirtyBytes())
759                 return true
760         })
761         return
762 }
763
764 // Bytes left to give in tracker announces.
765 func (t *Torrent) bytesLeftAnnounce() int64 {
766         if t.haveInfo() {
767                 return t.bytesLeft()
768         } else {
769                 return -1
770         }
771 }
772
773 func (t *Torrent) piecePartiallyDownloaded(piece pieceIndex) bool {
774         if t.pieceComplete(piece) {
775                 return false
776         }
777         if t.pieceAllDirty(piece) {
778                 return false
779         }
780         return t.pieces[piece].hasDirtyChunks()
781 }
782
783 func (t *Torrent) usualPieceSize() int {
784         return int(t.info.PieceLength)
785 }
786
787 func (t *Torrent) numPieces() pieceIndex {
788         return pieceIndex(t.info.NumPieces())
789 }
790
791 func (t *Torrent) numPiecesCompleted() (num pieceIndex) {
792         return pieceIndex(t._completedPieces.GetCardinality())
793 }
794
795 func (t *Torrent) close(wg *sync.WaitGroup) (err error) {
796         t.closed.Set()
797         if t.storage != nil {
798                 wg.Add(1)
799                 go func() {
800                         defer wg.Done()
801                         t.storageLock.Lock()
802                         defer t.storageLock.Unlock()
803                         if f := t.storage.Close; f != nil {
804                                 err1 := f()
805                                 if err1 != nil {
806                                         t.logger.WithDefaultLevel(log.Warning).Printf("error closing storage: %v", err1)
807                                 }
808                         }
809                 }()
810         }
811         t.iterPeers(func(p *Peer) {
812                 p.close()
813         })
814         t.pex.Reset()
815         t.cl.event.Broadcast()
816         t.pieceStateChanges.Close()
817         t.updateWantPeersEvent()
818         return
819 }
820
821 func (t *Torrent) requestOffset(r Request) int64 {
822         return torrentRequestOffset(*t.length, int64(t.usualPieceSize()), r)
823 }
824
825 // Return the request that would include the given offset into the torrent data. Returns !ok if
826 // there is no such request.
827 func (t *Torrent) offsetRequest(off int64) (req Request, ok bool) {
828         return torrentOffsetRequest(*t.length, t.info.PieceLength, int64(t.chunkSize), off)
829 }
830
831 func (t *Torrent) writeChunk(piece int, begin int64, data []byte) (err error) {
832         defer perf.ScopeTimerErr(&err)()
833         n, err := t.pieces[piece].Storage().WriteAt(data, begin)
834         if err == nil && n != len(data) {
835                 err = io.ErrShortWrite
836         }
837         return err
838 }
839
840 func (t *Torrent) bitfield() (bf []bool) {
841         bf = make([]bool, t.numPieces())
842         t._completedPieces.Iterate(func(piece uint32) (again bool) {
843                 bf[piece] = true
844                 return true
845         })
846         return
847 }
848
849 func (t *Torrent) pieceNumChunks(piece pieceIndex) chunkIndexType {
850         return chunkIndexType((t.pieceLength(piece) + t.chunkSize - 1) / t.chunkSize)
851 }
852
853 func (t *Torrent) chunksPerRegularPiece() uint32 {
854         return uint32((pp.Integer(t.usualPieceSize()) + t.chunkSize - 1) / t.chunkSize)
855 }
856
857 func (t *Torrent) numRequests() RequestIndex {
858         if t.numPieces() == 0 {
859                 return 0
860         }
861         return uint32(t.numPieces()-1)*t.chunksPerRegularPiece() + t.pieceNumChunks(t.numPieces()-1)
862 }
863
864 func (t *Torrent) pendAllChunkSpecs(pieceIndex pieceIndex) {
865         t.dirtyChunks.RemoveRange(
866                 uint64(t.pieceRequestIndexOffset(pieceIndex)),
867                 uint64(t.pieceRequestIndexOffset(pieceIndex+1)))
868 }
869
870 func (t *Torrent) pieceLength(piece pieceIndex) pp.Integer {
871         if t.info.PieceLength == 0 {
872                 // There will be no variance amongst pieces. Only pain.
873                 return 0
874         }
875         if piece == t.numPieces()-1 {
876                 ret := pp.Integer(*t.length % t.info.PieceLength)
877                 if ret != 0 {
878                         return ret
879                 }
880         }
881         return pp.Integer(t.info.PieceLength)
882 }
883
884 func (t *Torrent) hashPiece(piece pieceIndex) (ret metainfo.Hash, err error) {
885         p := t.piece(piece)
886         p.waitNoPendingWrites()
887         storagePiece := t.pieces[piece].Storage()
888
889         // Does the backend want to do its own hashing?
890         if i, ok := storagePiece.PieceImpl.(storage.SelfHashing); ok {
891                 var sum metainfo.Hash
892                 // log.Printf("A piece decided to self-hash: %d", piece)
893                 sum, err = i.SelfHash()
894                 missinggo.CopyExact(&ret, sum)
895                 return
896         }
897
898         hash := pieceHash.New()
899         const logPieceContents = false
900         if logPieceContents {
901                 var examineBuf bytes.Buffer
902                 _, err = storagePiece.WriteTo(io.MultiWriter(hash, &examineBuf))
903                 log.Printf("hashed %q with copy err %v", examineBuf.Bytes(), err)
904         } else {
905                 _, err = storagePiece.WriteTo(hash)
906         }
907         missinggo.CopyExact(&ret, hash.Sum(nil))
908         return
909 }
910
911 func (t *Torrent) haveAnyPieces() bool {
912         return t._completedPieces.GetCardinality() != 0
913 }
914
915 func (t *Torrent) haveAllPieces() bool {
916         if !t.haveInfo() {
917                 return false
918         }
919         return t._completedPieces.GetCardinality() == bitmap.BitRange(t.numPieces())
920 }
921
922 func (t *Torrent) havePiece(index pieceIndex) bool {
923         return t.haveInfo() && t.pieceComplete(index)
924 }
925
926 func (t *Torrent) maybeDropMutuallyCompletePeer(
927         // I'm not sure about taking peer here, not all peer implementations actually drop. Maybe that's
928         // okay?
929         p *Peer,
930 ) {
931         if !t.cl.config.DropMutuallyCompletePeers {
932                 return
933         }
934         if !t.haveAllPieces() {
935                 return
936         }
937         if all, known := p.peerHasAllPieces(); !(known && all) {
938                 return
939         }
940         if p.useful() {
941                 return
942         }
943         t.logger.WithDefaultLevel(log.Debug).Printf("dropping %v, which is mutually complete", p)
944         p.drop()
945 }
946
947 func (t *Torrent) haveChunk(r Request) (ret bool) {
948         // defer func() {
949         //      log.Println("have chunk", r, ret)
950         // }()
951         if !t.haveInfo() {
952                 return false
953         }
954         if t.pieceComplete(pieceIndex(r.Index)) {
955                 return true
956         }
957         p := &t.pieces[r.Index]
958         return !p.pendingChunk(r.ChunkSpec, t.chunkSize)
959 }
960
961 func chunkIndexFromChunkSpec(cs ChunkSpec, chunkSize pp.Integer) chunkIndexType {
962         return chunkIndexType(cs.Begin / chunkSize)
963 }
964
965 func (t *Torrent) wantPieceIndex(index pieceIndex) bool {
966         return t._pendingPieces.Contains(uint32(index))
967 }
968
969 // A pool of []*PeerConn, to reduce allocations in functions that need to index or sort Torrent
970 // conns (which is a map).
971 var peerConnSlices sync.Pool
972
973 // The worst connection is one that hasn't been sent, or sent anything useful for the longest. A bad
974 // connection is one that usually sends us unwanted pieces, or has been in the worse half of the
975 // established connections for more than a minute. This is O(n log n). If there was a way to not
976 // consider the position of a conn relative to the total number, it could be reduced to O(n).
977 func (t *Torrent) worstBadConn() (ret *PeerConn) {
978         var sl []*PeerConn
979         getInterface := peerConnSlices.Get()
980         if getInterface == nil {
981                 sl = make([]*PeerConn, 0, len(t.conns))
982         } else {
983                 sl = getInterface.([]*PeerConn)[:0]
984         }
985         sl = t.appendUnclosedConns(sl)
986         defer peerConnSlices.Put(sl)
987         wcs := worseConnSlice{sl}
988         heap.Init(&wcs)
989         for wcs.Len() != 0 {
990                 c := heap.Pop(&wcs).(*PeerConn)
991                 if c._stats.ChunksReadWasted.Int64() >= 6 && c._stats.ChunksReadWasted.Int64() > c._stats.ChunksReadUseful.Int64() {
992                         return c
993                 }
994                 // If the connection is in the worst half of the established
995                 // connection quota and is older than a minute.
996                 if wcs.Len() >= (t.maxEstablishedConns+1)/2 {
997                         // Give connections 1 minute to prove themselves.
998                         if time.Since(c.completedHandshake) > time.Minute {
999                                 return c
1000                         }
1001                 }
1002         }
1003         return nil
1004 }
1005
1006 type PieceStateChange struct {
1007         Index int
1008         PieceState
1009 }
1010
1011 func (t *Torrent) publishPieceChange(piece pieceIndex) {
1012         t.cl._mu.Defer(func() {
1013                 cur := t.pieceState(piece)
1014                 p := &t.pieces[piece]
1015                 if cur != p.publicPieceState {
1016                         p.publicPieceState = cur
1017                         t.pieceStateChanges.Publish(PieceStateChange{
1018                                 int(piece),
1019                                 cur,
1020                         })
1021                 }
1022         })
1023 }
1024
1025 func (t *Torrent) pieceNumPendingChunks(piece pieceIndex) pp.Integer {
1026         if t.pieceComplete(piece) {
1027                 return 0
1028         }
1029         return pp.Integer(t.pieceNumChunks(piece) - t.pieces[piece].numDirtyChunks())
1030 }
1031
1032 func (t *Torrent) pieceAllDirty(piece pieceIndex) bool {
1033         return t.pieces[piece].allChunksDirty()
1034 }
1035
1036 func (t *Torrent) readersChanged() {
1037         t.updateReaderPieces()
1038         t.updateAllPiecePriorities("Torrent.readersChanged")
1039 }
1040
1041 func (t *Torrent) updateReaderPieces() {
1042         t._readerNowPieces, t._readerReadaheadPieces = t.readerPiecePriorities()
1043 }
1044
1045 func (t *Torrent) readerPosChanged(from, to pieceRange) {
1046         if from == to {
1047                 return
1048         }
1049         t.updateReaderPieces()
1050         // Order the ranges, high and low.
1051         l, h := from, to
1052         if l.begin > h.begin {
1053                 l, h = h, l
1054         }
1055         if l.end < h.begin {
1056                 // Two distinct ranges.
1057                 t.updatePiecePriorities(l.begin, l.end, "Torrent.readerPosChanged")
1058                 t.updatePiecePriorities(h.begin, h.end, "Torrent.readerPosChanged")
1059         } else {
1060                 // Ranges overlap.
1061                 end := l.end
1062                 if h.end > end {
1063                         end = h.end
1064                 }
1065                 t.updatePiecePriorities(l.begin, end, "Torrent.readerPosChanged")
1066         }
1067 }
1068
1069 func (t *Torrent) maybeNewConns() {
1070         // Tickle the accept routine.
1071         t.cl.event.Broadcast()
1072         t.openNewConns()
1073 }
1074
1075 func (t *Torrent) piecePriorityChanged(piece pieceIndex, reason string) {
1076         if t._pendingPieces.Contains(uint32(piece)) {
1077                 t.iterPeers(func(c *Peer) {
1078                         if c.actualRequestState.Interested {
1079                                 return
1080                         }
1081                         if !c.isLowOnRequests() {
1082                                 return
1083                         }
1084                         if !c.peerHasPiece(piece) {
1085                                 return
1086                         }
1087                         c.updateRequests(reason)
1088                 })
1089         }
1090         t.maybeNewConns()
1091         t.publishPieceChange(piece)
1092 }
1093
1094 func (t *Torrent) updatePiecePriority(piece pieceIndex, reason string) {
1095         p := &t.pieces[piece]
1096         newPrio := p.uncachedPriority()
1097         // t.logger.Printf("torrent %p: piece %d: uncached priority: %v", t, piece, newPrio)
1098         if newPrio == PiecePriorityNone {
1099                 if !t._pendingPieces.CheckedRemove(uint32(piece)) {
1100                         return
1101                 }
1102         } else {
1103                 if !t._pendingPieces.CheckedAdd(uint32(piece)) {
1104                         return
1105                 }
1106         }
1107         t.piecePriorityChanged(piece, reason)
1108 }
1109
1110 func (t *Torrent) updateAllPiecePriorities(reason string) {
1111         t.updatePiecePriorities(0, t.numPieces(), reason)
1112 }
1113
1114 // Update all piece priorities in one hit. This function should have the same
1115 // output as updatePiecePriority, but across all pieces.
1116 func (t *Torrent) updatePiecePriorities(begin, end pieceIndex, reason string) {
1117         for i := begin; i < end; i++ {
1118                 t.updatePiecePriority(i, reason)
1119         }
1120 }
1121
1122 // Returns the range of pieces [begin, end) that contains the extent of bytes.
1123 func (t *Torrent) byteRegionPieces(off, size int64) (begin, end pieceIndex) {
1124         if off >= *t.length {
1125                 return
1126         }
1127         if off < 0 {
1128                 size += off
1129                 off = 0
1130         }
1131         if size <= 0 {
1132                 return
1133         }
1134         begin = pieceIndex(off / t.info.PieceLength)
1135         end = pieceIndex((off + size + t.info.PieceLength - 1) / t.info.PieceLength)
1136         if end > pieceIndex(t.info.NumPieces()) {
1137                 end = pieceIndex(t.info.NumPieces())
1138         }
1139         return
1140 }
1141
1142 // Returns true if all iterations complete without breaking. Returns the read regions for all
1143 // readers. The reader regions should not be merged as some callers depend on this method to
1144 // enumerate readers.
1145 func (t *Torrent) forReaderOffsetPieces(f func(begin, end pieceIndex) (more bool)) (all bool) {
1146         for r := range t.readers {
1147                 p := r.pieces
1148                 if p.begin >= p.end {
1149                         continue
1150                 }
1151                 if !f(p.begin, p.end) {
1152                         return false
1153                 }
1154         }
1155         return true
1156 }
1157
1158 func (t *Torrent) piecePriority(piece pieceIndex) piecePriority {
1159         return t.piece(piece).uncachedPriority()
1160 }
1161
1162 func (t *Torrent) pendRequest(req RequestIndex) {
1163         t.piece(int(req / t.chunksPerRegularPiece())).pendChunkIndex(req % t.chunksPerRegularPiece())
1164 }
1165
1166 func (t *Torrent) pieceCompletionChanged(piece pieceIndex, reason string) {
1167         t.cl.event.Broadcast()
1168         if t.pieceComplete(piece) {
1169                 t.onPieceCompleted(piece)
1170         } else {
1171                 t.onIncompletePiece(piece)
1172         }
1173         t.updatePiecePriority(piece, reason)
1174 }
1175
1176 func (t *Torrent) numReceivedConns() (ret int) {
1177         for c := range t.conns {
1178                 if c.Discovery == PeerSourceIncoming {
1179                         ret++
1180                 }
1181         }
1182         return
1183 }
1184
1185 func (t *Torrent) maxHalfOpen() int {
1186         // Note that if we somehow exceed the maximum established conns, we want
1187         // the negative value to have an effect.
1188         establishedHeadroom := int64(t.maxEstablishedConns - len(t.conns))
1189         extraIncoming := int64(t.numReceivedConns() - t.maxEstablishedConns/2)
1190         // We want to allow some experimentation with new peers, and to try to
1191         // upset an oversupply of received connections.
1192         return int(min(max(5, extraIncoming)+establishedHeadroom, int64(t.cl.config.HalfOpenConnsPerTorrent)))
1193 }
1194
1195 func (t *Torrent) openNewConns() (initiated int) {
1196         defer t.updateWantPeersEvent()
1197         for t.peers.Len() != 0 {
1198                 if !t.wantConns() {
1199                         return
1200                 }
1201                 if len(t.halfOpen) >= t.maxHalfOpen() {
1202                         return
1203                 }
1204                 if len(t.cl.dialers) == 0 {
1205                         return
1206                 }
1207                 if t.cl.numHalfOpen >= t.cl.config.TotalHalfOpenConns {
1208                         return
1209                 }
1210                 p := t.peers.PopMax()
1211                 t.initiateConn(p)
1212                 initiated++
1213         }
1214         return
1215 }
1216
1217 func (t *Torrent) updatePieceCompletion(piece pieceIndex) bool {
1218         p := t.piece(piece)
1219         uncached := t.pieceCompleteUncached(piece)
1220         cached := p.completion()
1221         changed := cached != uncached
1222         complete := uncached.Complete
1223         p.storageCompletionOk = uncached.Ok
1224         x := uint32(piece)
1225         if complete {
1226                 t._completedPieces.Add(x)
1227         } else {
1228                 t._completedPieces.Remove(x)
1229         }
1230         t.updateComplete()
1231         if complete && len(p.dirtiers) != 0 {
1232                 t.logger.Printf("marked piece %v complete but still has dirtiers", piece)
1233         }
1234         if changed {
1235                 log.Fstr("piece %d completion changed: %+v -> %+v", piece, cached, uncached).SetLevel(log.Debug).Log(t.logger)
1236                 t.pieceCompletionChanged(piece, "Torrent.updatePieceCompletion")
1237         }
1238         return changed
1239 }
1240
1241 // Non-blocking read. Client lock is not required.
1242 func (t *Torrent) readAt(b []byte, off int64) (n int, err error) {
1243         for len(b) != 0 {
1244                 p := &t.pieces[off/t.info.PieceLength]
1245                 p.waitNoPendingWrites()
1246                 var n1 int
1247                 n1, err = p.Storage().ReadAt(b, off-p.Info().Offset())
1248                 if n1 == 0 {
1249                         break
1250                 }
1251                 off += int64(n1)
1252                 n += n1
1253                 b = b[n1:]
1254         }
1255         return
1256 }
1257
1258 // Returns an error if the metadata was completed, but couldn't be set for some reason. Blame it on
1259 // the last peer to contribute. TODO: Actually we shouldn't blame peers for failure to open storage
1260 // etc. Also we should probably cached metadata pieces per-Peer, to isolate failure appropriately.
1261 func (t *Torrent) maybeCompleteMetadata() error {
1262         if t.haveInfo() {
1263                 // Nothing to do.
1264                 return nil
1265         }
1266         if !t.haveAllMetadataPieces() {
1267                 // Don't have enough metadata pieces.
1268                 return nil
1269         }
1270         err := t.setInfoBytesLocked(t.metadataBytes)
1271         if err != nil {
1272                 t.invalidateMetadata()
1273                 return fmt.Errorf("error setting info bytes: %s", err)
1274         }
1275         if t.cl.config.Debug {
1276                 t.logger.Printf("%s: got metadata from peers", t)
1277         }
1278         return nil
1279 }
1280
1281 func (t *Torrent) readerPiecePriorities() (now, readahead bitmap.Bitmap) {
1282         t.forReaderOffsetPieces(func(begin, end pieceIndex) bool {
1283                 if end > begin {
1284                         now.Add(bitmap.BitIndex(begin))
1285                         readahead.AddRange(bitmap.BitRange(begin)+1, bitmap.BitRange(end))
1286                 }
1287                 return true
1288         })
1289         return
1290 }
1291
1292 func (t *Torrent) needData() bool {
1293         if t.closed.IsSet() {
1294                 return false
1295         }
1296         if !t.haveInfo() {
1297                 return true
1298         }
1299         return !t._pendingPieces.IsEmpty()
1300 }
1301
1302 func appendMissingStrings(old, new []string) (ret []string) {
1303         ret = old
1304 new:
1305         for _, n := range new {
1306                 for _, o := range old {
1307                         if o == n {
1308                                 continue new
1309                         }
1310                 }
1311                 ret = append(ret, n)
1312         }
1313         return
1314 }
1315
1316 func appendMissingTrackerTiers(existing [][]string, minNumTiers int) (ret [][]string) {
1317         ret = existing
1318         for minNumTiers > len(ret) {
1319                 ret = append(ret, nil)
1320         }
1321         return
1322 }
1323
1324 func (t *Torrent) addTrackers(announceList [][]string) {
1325         fullAnnounceList := &t.metainfo.AnnounceList
1326         t.metainfo.AnnounceList = appendMissingTrackerTiers(*fullAnnounceList, len(announceList))
1327         for tierIndex, trackerURLs := range announceList {
1328                 (*fullAnnounceList)[tierIndex] = appendMissingStrings((*fullAnnounceList)[tierIndex], trackerURLs)
1329         }
1330         t.startMissingTrackerScrapers()
1331         t.updateWantPeersEvent()
1332 }
1333
1334 // Don't call this before the info is available.
1335 func (t *Torrent) bytesCompleted() int64 {
1336         if !t.haveInfo() {
1337                 return 0
1338         }
1339         return *t.length - t.bytesLeft()
1340 }
1341
1342 func (t *Torrent) SetInfoBytes(b []byte) (err error) {
1343         t.cl.lock()
1344         defer t.cl.unlock()
1345         return t.setInfoBytesLocked(b)
1346 }
1347
1348 // Returns true if connection is removed from torrent.Conns.
1349 func (t *Torrent) deletePeerConn(c *PeerConn) (ret bool) {
1350         if !c.closed.IsSet() {
1351                 panic("connection is not closed")
1352                 // There are behaviours prevented by the closed state that will fail
1353                 // if the connection has been deleted.
1354         }
1355         _, ret = t.conns[c]
1356         delete(t.conns, c)
1357         // Avoid adding a drop event more than once. Probably we should track whether we've generated
1358         // the drop event against the PexConnState instead.
1359         if ret {
1360                 if !t.cl.config.DisablePEX {
1361                         t.pex.Drop(c)
1362                 }
1363         }
1364         torrent.Add("deleted connections", 1)
1365         c.deleteAllRequests()
1366         t.assertPendingRequests()
1367         return
1368 }
1369
1370 func (t *Torrent) decPeerPieceAvailability(p *Peer) {
1371         if !t.haveInfo() {
1372                 return
1373         }
1374         p.newPeerPieces().Iterate(func(i uint32) bool {
1375                 p.t.decPieceAvailability(pieceIndex(i))
1376                 return true
1377         })
1378 }
1379
1380 func (t *Torrent) assertPendingRequests() {
1381         if !check {
1382                 return
1383         }
1384         var actual pendingRequests
1385         if t.haveInfo() {
1386                 actual.m = make([]int, t.numRequests())
1387         }
1388         t.iterPeers(func(p *Peer) {
1389                 p.actualRequestState.Requests.Iterate(func(x uint32) bool {
1390                         actual.Inc(x)
1391                         return true
1392                 })
1393         })
1394         diff := cmp.Diff(actual.m, t.pendingRequests.m)
1395         if diff != "" {
1396                 panic(diff)
1397         }
1398 }
1399
1400 func (t *Torrent) dropConnection(c *PeerConn) {
1401         t.cl.event.Broadcast()
1402         c.close()
1403         if t.deletePeerConn(c) {
1404                 t.openNewConns()
1405         }
1406 }
1407
1408 func (t *Torrent) wantPeers() bool {
1409         if t.closed.IsSet() {
1410                 return false
1411         }
1412         if t.peers.Len() > t.cl.config.TorrentPeersLowWater {
1413                 return false
1414         }
1415         return t.needData() || t.seeding()
1416 }
1417
1418 func (t *Torrent) updateWantPeersEvent() {
1419         if t.wantPeers() {
1420                 t.wantPeersEvent.Set()
1421         } else {
1422                 t.wantPeersEvent.Clear()
1423         }
1424 }
1425
1426 // Returns whether the client should make effort to seed the torrent.
1427 func (t *Torrent) seeding() bool {
1428         cl := t.cl
1429         if t.closed.IsSet() {
1430                 return false
1431         }
1432         if t.dataUploadDisallowed {
1433                 return false
1434         }
1435         if cl.config.NoUpload {
1436                 return false
1437         }
1438         if !cl.config.Seed {
1439                 return false
1440         }
1441         if cl.config.DisableAggressiveUpload && t.needData() {
1442                 return false
1443         }
1444         return true
1445 }
1446
1447 func (t *Torrent) onWebRtcConn(
1448         c datachannel.ReadWriteCloser,
1449         dcc webtorrent.DataChannelContext,
1450 ) {
1451         defer c.Close()
1452         pc, err := t.cl.initiateProtocolHandshakes(
1453                 context.Background(),
1454                 webrtcNetConn{c, dcc},
1455                 t,
1456                 dcc.LocalOffered,
1457                 false,
1458                 webrtcNetAddr{dcc.Remote},
1459                 webrtcNetwork,
1460                 fmt.Sprintf("webrtc offer_id %x", dcc.OfferId),
1461         )
1462         if err != nil {
1463                 t.logger.WithDefaultLevel(log.Error).Printf("error in handshaking webrtc connection: %v", err)
1464                 return
1465         }
1466         if dcc.LocalOffered {
1467                 pc.Discovery = PeerSourceTracker
1468         } else {
1469                 pc.Discovery = PeerSourceIncoming
1470         }
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 }