]> Sergey Matveev's repositories - btrtrc.git/blob - torrent.go
Avoid calling net.Conn methods with the Client mutex locked
[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         pc.conn.SetWriteDeadline(time.Time{})
1472         t.cl.lock()
1473         defer t.cl.unlock()
1474         err = t.cl.runHandshookConn(pc, t)
1475         if err != nil {
1476                 t.logger.WithDefaultLevel(log.Critical).Printf("error running handshook webrtc conn: %v", err)
1477         }
1478 }
1479
1480 func (t *Torrent) logRunHandshookConn(pc *PeerConn, logAll bool, level log.Level) {
1481         err := t.cl.runHandshookConn(pc, t)
1482         if err != nil || logAll {
1483                 t.logger.WithDefaultLevel(level).Printf("error running handshook conn: %v", err)
1484         }
1485 }
1486
1487 func (t *Torrent) runHandshookConnLoggingErr(pc *PeerConn) {
1488         t.logRunHandshookConn(pc, false, log.Debug)
1489 }
1490
1491 func (t *Torrent) startWebsocketAnnouncer(u url.URL) torrentTrackerAnnouncer {
1492         wtc, release := t.cl.websocketTrackers.Get(u.String())
1493         go func() {
1494                 <-t.closed.Done()
1495                 release()
1496         }()
1497         wst := websocketTrackerStatus{u, wtc}
1498         go func() {
1499                 err := wtc.Announce(tracker.Started, t.infoHash)
1500                 if err != nil {
1501                         t.logger.WithDefaultLevel(log.Warning).Printf(
1502                                 "error in initial announce to %q: %v",
1503                                 u.String(), err,
1504                         )
1505                 }
1506         }()
1507         return wst
1508 }
1509
1510 func (t *Torrent) startScrapingTracker(_url string) {
1511         if _url == "" {
1512                 return
1513         }
1514         u, err := url.Parse(_url)
1515         if err != nil {
1516                 // URLs with a leading '*' appear to be a uTorrent convention to
1517                 // disable trackers.
1518                 if _url[0] != '*' {
1519                         log.Str("error parsing tracker url").AddValues("url", _url).Log(t.logger)
1520                 }
1521                 return
1522         }
1523         if u.Scheme == "udp" {
1524                 u.Scheme = "udp4"
1525                 t.startScrapingTracker(u.String())
1526                 u.Scheme = "udp6"
1527                 t.startScrapingTracker(u.String())
1528                 return
1529         }
1530         if _, ok := t.trackerAnnouncers[_url]; ok {
1531                 return
1532         }
1533         sl := func() torrentTrackerAnnouncer {
1534                 switch u.Scheme {
1535                 case "ws", "wss":
1536                         if t.cl.config.DisableWebtorrent {
1537                                 return nil
1538                         }
1539                         return t.startWebsocketAnnouncer(*u)
1540                 case "udp4":
1541                         if t.cl.config.DisableIPv4Peers || t.cl.config.DisableIPv4 {
1542                                 return nil
1543                         }
1544                 case "udp6":
1545                         if t.cl.config.DisableIPv6 {
1546                                 return nil
1547                         }
1548                 }
1549                 newAnnouncer := &trackerScraper{
1550                         u:               *u,
1551                         t:               t,
1552                         lookupTrackerIp: t.cl.config.LookupTrackerIp,
1553                 }
1554                 go newAnnouncer.Run()
1555                 return newAnnouncer
1556         }()
1557         if sl == nil {
1558                 return
1559         }
1560         if t.trackerAnnouncers == nil {
1561                 t.trackerAnnouncers = make(map[string]torrentTrackerAnnouncer)
1562         }
1563         t.trackerAnnouncers[_url] = sl
1564 }
1565
1566 // Adds and starts tracker scrapers for tracker URLs that aren't already
1567 // running.
1568 func (t *Torrent) startMissingTrackerScrapers() {
1569         if t.cl.config.DisableTrackers {
1570                 return
1571         }
1572         t.startScrapingTracker(t.metainfo.Announce)
1573         for _, tier := range t.metainfo.AnnounceList {
1574                 for _, url := range tier {
1575                         t.startScrapingTracker(url)
1576                 }
1577         }
1578 }
1579
1580 // Returns an AnnounceRequest with fields filled out to defaults and current
1581 // values.
1582 func (t *Torrent) announceRequest(event tracker.AnnounceEvent) tracker.AnnounceRequest {
1583         // Note that IPAddress is not set. It's set for UDP inside the tracker code, since it's
1584         // dependent on the network in use.
1585         return tracker.AnnounceRequest{
1586                 Event: event,
1587                 NumWant: func() int32 {
1588                         if t.wantPeers() && len(t.cl.dialers) > 0 {
1589                                 return -1
1590                         } else {
1591                                 return 0
1592                         }
1593                 }(),
1594                 Port:     uint16(t.cl.incomingPeerPort()),
1595                 PeerId:   t.cl.peerID,
1596                 InfoHash: t.infoHash,
1597                 Key:      t.cl.announceKey(),
1598
1599                 // The following are vaguely described in BEP 3.
1600
1601                 Left:     t.bytesLeftAnnounce(),
1602                 Uploaded: t.stats.BytesWrittenData.Int64(),
1603                 // There's no mention of wasted or unwanted download in the BEP.
1604                 Downloaded: t.stats.BytesReadUsefulData.Int64(),
1605         }
1606 }
1607
1608 // Adds peers revealed in an announce until the announce ends, or we have
1609 // enough peers.
1610 func (t *Torrent) consumeDhtAnnouncePeers(pvs <-chan dht.PeersValues) {
1611         cl := t.cl
1612         for v := range pvs {
1613                 cl.lock()
1614                 added := 0
1615                 for _, cp := range v.Peers {
1616                         if cp.Port == 0 {
1617                                 // Can't do anything with this.
1618                                 continue
1619                         }
1620                         if t.addPeer(PeerInfo{
1621                                 Addr:   ipPortAddr{cp.IP, cp.Port},
1622                                 Source: PeerSourceDhtGetPeers,
1623                         }) {
1624                                 added++
1625                         }
1626                 }
1627                 cl.unlock()
1628                 // if added != 0 {
1629                 //      log.Printf("added %v peers from dht for %v", added, t.InfoHash().HexString())
1630                 // }
1631         }
1632 }
1633
1634 // Announce using the provided DHT server. Peers are consumed automatically. done is closed when the
1635 // announce ends. stop will force the announce to end.
1636 func (t *Torrent) AnnounceToDht(s DhtServer) (done <-chan struct{}, stop func(), err error) {
1637         ps, err := s.Announce(t.infoHash, t.cl.incomingPeerPort(), true)
1638         if err != nil {
1639                 return
1640         }
1641         _done := make(chan struct{})
1642         done = _done
1643         stop = ps.Close
1644         go func() {
1645                 t.consumeDhtAnnouncePeers(ps.Peers())
1646                 close(_done)
1647         }()
1648         return
1649 }
1650
1651 func (t *Torrent) timeboxedAnnounceToDht(s DhtServer) error {
1652         _, stop, err := t.AnnounceToDht(s)
1653         if err != nil {
1654                 return err
1655         }
1656         select {
1657         case <-t.closed.Done():
1658         case <-time.After(5 * time.Minute):
1659         }
1660         stop()
1661         return nil
1662 }
1663
1664 func (t *Torrent) dhtAnnouncer(s DhtServer) {
1665         cl := t.cl
1666         cl.lock()
1667         defer cl.unlock()
1668         for {
1669                 for {
1670                         if t.closed.IsSet() {
1671                                 return
1672                         }
1673                         if !t.wantPeers() {
1674                                 goto wait
1675                         }
1676                         // TODO: Determine if there's a listener on the port we're announcing.
1677                         if len(cl.dialers) == 0 && len(cl.listeners) == 0 {
1678                                 goto wait
1679                         }
1680                         break
1681                 wait:
1682                         cl.event.Wait()
1683                 }
1684                 func() {
1685                         t.numDHTAnnounces++
1686                         cl.unlock()
1687                         defer cl.lock()
1688                         err := t.timeboxedAnnounceToDht(s)
1689                         if err != nil {
1690                                 t.logger.WithDefaultLevel(log.Warning).Printf("error announcing %q to DHT: %s", t, err)
1691                         }
1692                 }()
1693         }
1694 }
1695
1696 func (t *Torrent) addPeers(peers []PeerInfo) (added int) {
1697         for _, p := range peers {
1698                 if t.addPeer(p) {
1699                         added++
1700                 }
1701         }
1702         return
1703 }
1704
1705 // The returned TorrentStats may require alignment in memory. See
1706 // https://github.com/anacrolix/torrent/issues/383.
1707 func (t *Torrent) Stats() TorrentStats {
1708         t.cl.rLock()
1709         defer t.cl.rUnlock()
1710         return t.statsLocked()
1711 }
1712
1713 func (t *Torrent) statsLocked() (ret TorrentStats) {
1714         ret.ActivePeers = len(t.conns)
1715         ret.HalfOpenPeers = len(t.halfOpen)
1716         ret.PendingPeers = t.peers.Len()
1717         ret.TotalPeers = t.numTotalPeers()
1718         ret.ConnectedSeeders = 0
1719         for c := range t.conns {
1720                 if all, ok := c.peerHasAllPieces(); all && ok {
1721                         ret.ConnectedSeeders++
1722                 }
1723         }
1724         ret.ConnStats = t.stats.Copy()
1725         ret.PiecesComplete = t.numPiecesCompleted()
1726         return
1727 }
1728
1729 // The total number of peers in the torrent.
1730 func (t *Torrent) numTotalPeers() int {
1731         peers := make(map[string]struct{})
1732         for conn := range t.conns {
1733                 ra := conn.conn.RemoteAddr()
1734                 if ra == nil {
1735                         // It's been closed and doesn't support RemoteAddr.
1736                         continue
1737                 }
1738                 peers[ra.String()] = struct{}{}
1739         }
1740         for addr := range t.halfOpen {
1741                 peers[addr] = struct{}{}
1742         }
1743         t.peers.Each(func(peer PeerInfo) {
1744                 peers[peer.Addr.String()] = struct{}{}
1745         })
1746         return len(peers)
1747 }
1748
1749 // Reconcile bytes transferred before connection was associated with a
1750 // torrent.
1751 func (t *Torrent) reconcileHandshakeStats(c *PeerConn) {
1752         if c._stats != (ConnStats{
1753                 // Handshakes should only increment these fields:
1754                 BytesWritten: c._stats.BytesWritten,
1755                 BytesRead:    c._stats.BytesRead,
1756         }) {
1757                 panic("bad stats")
1758         }
1759         c.postHandshakeStats(func(cs *ConnStats) {
1760                 cs.BytesRead.Add(c._stats.BytesRead.Int64())
1761                 cs.BytesWritten.Add(c._stats.BytesWritten.Int64())
1762         })
1763         c.reconciledHandshakeStats = true
1764 }
1765
1766 // Returns true if the connection is added.
1767 func (t *Torrent) addPeerConn(c *PeerConn) (err error) {
1768         defer func() {
1769                 if err == nil {
1770                         torrent.Add("added connections", 1)
1771                 }
1772         }()
1773         if t.closed.IsSet() {
1774                 return errors.New("torrent closed")
1775         }
1776         for c0 := range t.conns {
1777                 if c.PeerID != c0.PeerID {
1778                         continue
1779                 }
1780                 if !t.cl.config.DropDuplicatePeerIds {
1781                         continue
1782                 }
1783                 if left, ok := c.hasPreferredNetworkOver(c0); ok && left {
1784                         c0.close()
1785                         t.deletePeerConn(c0)
1786                 } else {
1787                         return errors.New("existing connection preferred")
1788                 }
1789         }
1790         if len(t.conns) >= t.maxEstablishedConns {
1791                 c := t.worstBadConn()
1792                 if c == nil {
1793                         return errors.New("don't want conns")
1794                 }
1795                 c.close()
1796                 t.deletePeerConn(c)
1797         }
1798         if len(t.conns) >= t.maxEstablishedConns {
1799                 panic(len(t.conns))
1800         }
1801         t.conns[c] = struct{}{}
1802         if !t.cl.config.DisablePEX && !c.PeerExtensionBytes.SupportsExtended() {
1803                 t.pex.Add(c) // as no further extended handshake expected
1804         }
1805         return nil
1806 }
1807
1808 func (t *Torrent) wantConns() bool {
1809         if !t.networkingEnabled.Bool() {
1810                 return false
1811         }
1812         if t.closed.IsSet() {
1813                 return false
1814         }
1815         if !t.seeding() && !t.needData() {
1816                 return false
1817         }
1818         if len(t.conns) < t.maxEstablishedConns {
1819                 return true
1820         }
1821         return t.worstBadConn() != nil
1822 }
1823
1824 func (t *Torrent) SetMaxEstablishedConns(max int) (oldMax int) {
1825         t.cl.lock()
1826         defer t.cl.unlock()
1827         oldMax = t.maxEstablishedConns
1828         t.maxEstablishedConns = max
1829         wcs := slices.HeapInterface(slices.FromMapKeys(t.conns), func(l, r *PeerConn) bool {
1830                 return worseConn(&l.Peer, &r.Peer)
1831         })
1832         for len(t.conns) > t.maxEstablishedConns && wcs.Len() > 0 {
1833                 t.dropConnection(wcs.Pop().(*PeerConn))
1834         }
1835         t.openNewConns()
1836         return oldMax
1837 }
1838
1839 func (t *Torrent) pieceHashed(piece pieceIndex, passed bool, hashIoErr error) {
1840         t.logger.Log(log.Fstr("hashed piece %d (passed=%t)", piece, passed).SetLevel(log.Debug))
1841         p := t.piece(piece)
1842         p.numVerifies++
1843         t.cl.event.Broadcast()
1844         if t.closed.IsSet() {
1845                 return
1846         }
1847
1848         // Don't score the first time a piece is hashed, it could be an initial check.
1849         if p.storageCompletionOk {
1850                 if passed {
1851                         pieceHashedCorrect.Add(1)
1852                 } else {
1853                         log.Fmsg(
1854                                 "piece %d failed hash: %d connections contributed", piece, len(p.dirtiers),
1855                         ).AddValues(t, p).SetLevel(log.Debug).Log(t.logger)
1856                         pieceHashedNotCorrect.Add(1)
1857                 }
1858         }
1859
1860         p.marking = true
1861         t.publishPieceChange(piece)
1862         defer func() {
1863                 p.marking = false
1864                 t.publishPieceChange(piece)
1865         }()
1866
1867         if passed {
1868                 if len(p.dirtiers) != 0 {
1869                         // Don't increment stats above connection-level for every involved connection.
1870                         t.allStats((*ConnStats).incrementPiecesDirtiedGood)
1871                 }
1872                 for c := range p.dirtiers {
1873                         c._stats.incrementPiecesDirtiedGood()
1874                 }
1875                 t.clearPieceTouchers(piece)
1876                 t.cl.unlock()
1877                 err := p.Storage().MarkComplete()
1878                 if err != nil {
1879                         t.logger.Printf("%T: error marking piece complete %d: %s", t.storage, piece, err)
1880                 }
1881                 t.cl.lock()
1882
1883                 if t.closed.IsSet() {
1884                         return
1885                 }
1886                 t.pendAllChunkSpecs(piece)
1887         } else {
1888                 if len(p.dirtiers) != 0 && p.allChunksDirty() && hashIoErr == nil {
1889                         // Peers contributed to all the data for this piece hash failure, and the failure was
1890                         // not due to errors in the storage (such as data being dropped in a cache).
1891
1892                         // Increment Torrent and above stats, and then specific connections.
1893                         t.allStats((*ConnStats).incrementPiecesDirtiedBad)
1894                         for c := range p.dirtiers {
1895                                 // Y u do dis peer?!
1896                                 c.stats().incrementPiecesDirtiedBad()
1897                         }
1898
1899                         bannableTouchers := make([]*Peer, 0, len(p.dirtiers))
1900                         for c := range p.dirtiers {
1901                                 if !c.trusted {
1902                                         bannableTouchers = append(bannableTouchers, c)
1903                                 }
1904                         }
1905                         t.clearPieceTouchers(piece)
1906                         slices.Sort(bannableTouchers, connLessTrusted)
1907
1908                         if t.cl.config.Debug {
1909                                 t.logger.Printf(
1910                                         "bannable conns by trust for piece %d: %v",
1911                                         piece,
1912                                         func() (ret []connectionTrust) {
1913                                                 for _, c := range bannableTouchers {
1914                                                         ret = append(ret, c.trust())
1915                                                 }
1916                                                 return
1917                                         }(),
1918                                 )
1919                         }
1920
1921                         if len(bannableTouchers) >= 1 {
1922                                 c := bannableTouchers[0]
1923                                 t.cl.banPeerIP(c.remoteIp())
1924                                 c.drop()
1925                         }
1926                 }
1927                 t.onIncompletePiece(piece)
1928                 p.Storage().MarkNotComplete()
1929         }
1930         t.updatePieceCompletion(piece)
1931 }
1932
1933 func (t *Torrent) cancelRequestsForPiece(piece pieceIndex) {
1934         // TODO: Make faster
1935         for cn := range t.conns {
1936                 cn.tickleWriter()
1937         }
1938 }
1939
1940 func (t *Torrent) onPieceCompleted(piece pieceIndex) {
1941         t.pendAllChunkSpecs(piece)
1942         t.cancelRequestsForPiece(piece)
1943         t.piece(piece).readerCond.Broadcast()
1944         for conn := range t.conns {
1945                 conn.have(piece)
1946                 t.maybeDropMutuallyCompletePeer(&conn.Peer)
1947         }
1948 }
1949
1950 // Called when a piece is found to be not complete.
1951 func (t *Torrent) onIncompletePiece(piece pieceIndex) {
1952         if t.pieceAllDirty(piece) {
1953                 t.pendAllChunkSpecs(piece)
1954         }
1955         if !t.wantPieceIndex(piece) {
1956                 // t.logger.Printf("piece %d incomplete and unwanted", piece)
1957                 return
1958         }
1959         // We could drop any connections that we told we have a piece that we
1960         // don't here. But there's a test failure, and it seems clients don't care
1961         // if you request pieces that you already claim to have. Pruning bad
1962         // connections might just remove any connections that aren't treating us
1963         // favourably anyway.
1964
1965         // for c := range t.conns {
1966         //      if c.sentHave(piece) {
1967         //              c.drop()
1968         //      }
1969         // }
1970         t.iterPeers(func(conn *Peer) {
1971                 if conn.peerHasPiece(piece) {
1972                         conn.updateRequests("piece incomplete")
1973                 }
1974         })
1975 }
1976
1977 func (t *Torrent) tryCreateMorePieceHashers() {
1978         for !t.closed.IsSet() && t.activePieceHashes < 2 && t.tryCreatePieceHasher() {
1979         }
1980 }
1981
1982 func (t *Torrent) tryCreatePieceHasher() bool {
1983         if t.storage == nil {
1984                 return false
1985         }
1986         pi, ok := t.getPieceToHash()
1987         if !ok {
1988                 return false
1989         }
1990         p := t.piece(pi)
1991         t.piecesQueuedForHash.Remove(bitmap.BitIndex(pi))
1992         p.hashing = true
1993         t.publishPieceChange(pi)
1994         t.updatePiecePriority(pi, "Torrent.tryCreatePieceHasher")
1995         t.storageLock.RLock()
1996         t.activePieceHashes++
1997         go t.pieceHasher(pi)
1998         return true
1999 }
2000
2001 func (t *Torrent) getPieceToHash() (ret pieceIndex, ok bool) {
2002         t.piecesQueuedForHash.IterTyped(func(i pieceIndex) bool {
2003                 if t.piece(i).hashing {
2004                         return true
2005                 }
2006                 ret = i
2007                 ok = true
2008                 return false
2009         })
2010         return
2011 }
2012
2013 func (t *Torrent) pieceHasher(index pieceIndex) {
2014         p := t.piece(index)
2015         sum, copyErr := t.hashPiece(index)
2016         correct := sum == *p.hash
2017         switch copyErr {
2018         case nil, io.EOF:
2019         default:
2020                 log.Fmsg("piece %v (%s) hash failure copy error: %v", p, p.hash.HexString(), copyErr).Log(t.logger)
2021         }
2022         t.storageLock.RUnlock()
2023         t.cl.lock()
2024         defer t.cl.unlock()
2025         p.hashing = false
2026         t.pieceHashed(index, correct, copyErr)
2027         t.updatePiecePriority(index, "Torrent.pieceHasher")
2028         t.activePieceHashes--
2029         t.tryCreateMorePieceHashers()
2030 }
2031
2032 // Return the connections that touched a piece, and clear the entries while doing it.
2033 func (t *Torrent) clearPieceTouchers(pi pieceIndex) {
2034         p := t.piece(pi)
2035         for c := range p.dirtiers {
2036                 delete(c.peerTouchedPieces, pi)
2037                 delete(p.dirtiers, c)
2038         }
2039 }
2040
2041 func (t *Torrent) peersAsSlice() (ret []*Peer) {
2042         t.iterPeers(func(p *Peer) {
2043                 ret = append(ret, p)
2044         })
2045         return
2046 }
2047
2048 func (t *Torrent) queuePieceCheck(pieceIndex pieceIndex) {
2049         piece := t.piece(pieceIndex)
2050         if piece.queuedForHash() {
2051                 return
2052         }
2053         t.piecesQueuedForHash.Add(bitmap.BitIndex(pieceIndex))
2054         t.publishPieceChange(pieceIndex)
2055         t.updatePiecePriority(pieceIndex, "Torrent.queuePieceCheck")
2056         t.tryCreateMorePieceHashers()
2057 }
2058
2059 // Forces all the pieces to be re-hashed. See also Piece.VerifyData. This should not be called
2060 // before the Info is available.
2061 func (t *Torrent) VerifyData() {
2062         for i := pieceIndex(0); i < t.NumPieces(); i++ {
2063                 t.Piece(i).VerifyData()
2064         }
2065 }
2066
2067 // Start the process of connecting to the given peer for the given torrent if appropriate.
2068 func (t *Torrent) initiateConn(peer PeerInfo) {
2069         if peer.Id == t.cl.peerID {
2070                 return
2071         }
2072         if t.cl.badPeerAddr(peer.Addr) && !peer.Trusted {
2073                 return
2074         }
2075         addr := peer.Addr
2076         if t.addrActive(addr.String()) {
2077                 return
2078         }
2079         t.cl.numHalfOpen++
2080         t.halfOpen[addr.String()] = peer
2081         go t.cl.outgoingConnection(t, addr, peer.Source, peer.Trusted)
2082 }
2083
2084 // Adds a trusted, pending peer for each of the given Client's addresses. Typically used in tests to
2085 // quickly make one Client visible to the Torrent of another Client.
2086 func (t *Torrent) AddClientPeer(cl *Client) int {
2087         return t.AddPeers(func() (ps []PeerInfo) {
2088                 for _, la := range cl.ListenAddrs() {
2089                         ps = append(ps, PeerInfo{
2090                                 Addr:    la,
2091                                 Trusted: true,
2092                         })
2093                 }
2094                 return
2095         }())
2096 }
2097
2098 // All stats that include this Torrent. Useful when we want to increment ConnStats but not for every
2099 // connection.
2100 func (t *Torrent) allStats(f func(*ConnStats)) {
2101         f(&t.stats)
2102         f(&t.cl.stats)
2103 }
2104
2105 func (t *Torrent) hashingPiece(i pieceIndex) bool {
2106         return t.pieces[i].hashing
2107 }
2108
2109 func (t *Torrent) pieceQueuedForHash(i pieceIndex) bool {
2110         return t.piecesQueuedForHash.Get(bitmap.BitIndex(i))
2111 }
2112
2113 func (t *Torrent) dialTimeout() time.Duration {
2114         return reducedDialTimeout(t.cl.config.MinDialTimeout, t.cl.config.NominalDialTimeout, t.cl.config.HalfOpenConnsPerTorrent, t.peers.Len())
2115 }
2116
2117 func (t *Torrent) piece(i int) *Piece {
2118         return &t.pieces[i]
2119 }
2120
2121 func (t *Torrent) onWriteChunkErr(err error) {
2122         if t.userOnWriteChunkErr != nil {
2123                 go t.userOnWriteChunkErr(err)
2124                 return
2125         }
2126         t.logger.WithDefaultLevel(log.Critical).Printf("default chunk write error handler: disabling data download")
2127         t.disallowDataDownloadLocked()
2128 }
2129
2130 func (t *Torrent) DisallowDataDownload() {
2131         t.disallowDataDownloadLocked()
2132 }
2133
2134 func (t *Torrent) disallowDataDownloadLocked() {
2135         t.dataDownloadDisallowed.Set()
2136 }
2137
2138 func (t *Torrent) AllowDataDownload() {
2139         t.dataDownloadDisallowed.Clear()
2140 }
2141
2142 // Enables uploading data, if it was disabled.
2143 func (t *Torrent) AllowDataUpload() {
2144         t.cl.lock()
2145         defer t.cl.unlock()
2146         t.dataUploadDisallowed = false
2147         for c := range t.conns {
2148                 c.updateRequests("allow data upload")
2149         }
2150 }
2151
2152 // Disables uploading data, if it was enabled.
2153 func (t *Torrent) DisallowDataUpload() {
2154         t.cl.lock()
2155         defer t.cl.unlock()
2156         t.dataUploadDisallowed = true
2157         for c := range t.conns {
2158                 c.updateRequests("disallow data upload")
2159         }
2160 }
2161
2162 // Sets a handler that is called if there's an error writing a chunk to local storage. By default,
2163 // or if nil, a critical message is logged, and data download is disabled.
2164 func (t *Torrent) SetOnWriteChunkError(f func(error)) {
2165         t.cl.lock()
2166         defer t.cl.unlock()
2167         t.userOnWriteChunkErr = f
2168 }
2169
2170 func (t *Torrent) iterPeers(f func(p *Peer)) {
2171         for pc := range t.conns {
2172                 f(&pc.Peer)
2173         }
2174         for _, ws := range t.webSeeds {
2175                 f(ws)
2176         }
2177 }
2178
2179 func (t *Torrent) callbacks() *Callbacks {
2180         return &t.cl.config.Callbacks
2181 }
2182
2183 func (t *Torrent) addWebSeed(url string) {
2184         if t.cl.config.DisableWebseeds {
2185                 return
2186         }
2187         if _, ok := t.webSeeds[url]; ok {
2188                 return
2189         }
2190         // I don't think Go http supports pipelining requests. However we can have more ready to go
2191         // right away. This value should be some multiple of the number of connections to a host. I
2192         // would expect that double maxRequests plus a bit would be appropriate.
2193         const maxRequests = 32
2194         ws := webseedPeer{
2195                 peer: Peer{
2196                         t:                        t,
2197                         outgoing:                 true,
2198                         Network:                  "http",
2199                         reconciledHandshakeStats: true,
2200                         // This should affect how often we have to recompute requests for this peer. Note that
2201                         // because we can request more than 1 thing at a time over HTTP, we will hit the low
2202                         // requests mark more often, so recomputation is probably sooner than with regular peer
2203                         // conns. ~4x maxRequests would be about right.
2204                         PeerMaxRequests: 128,
2205                         RemoteAddr:      remoteAddrFromUrl(url),
2206                         callbacks:       t.callbacks(),
2207                 },
2208                 client: webseed.Client{
2209                         HttpClient: t.cl.webseedHttpClient,
2210                         Url:        url,
2211                 },
2212                 activeRequests: make(map[Request]webseed.Request, maxRequests),
2213                 maxRequests:    maxRequests,
2214         }
2215         ws.peer.initUpdateRequestsTimer()
2216         ws.requesterCond.L = t.cl.locker()
2217         for i := 0; i < maxRequests; i += 1 {
2218                 go ws.requester()
2219         }
2220         for _, f := range t.callbacks().NewPeer {
2221                 f(&ws.peer)
2222         }
2223         ws.peer.logger = t.logger.WithContextValue(&ws)
2224         ws.peer.peerImpl = &ws
2225         if t.haveInfo() {
2226                 ws.onGotInfo(t.info)
2227         }
2228         t.webSeeds[url] = &ws.peer
2229 }
2230
2231 func (t *Torrent) peerIsActive(p *Peer) (active bool) {
2232         t.iterPeers(func(p1 *Peer) {
2233                 if p1 == p {
2234                         active = true
2235                 }
2236         })
2237         return
2238 }
2239
2240 func (t *Torrent) requestIndexToRequest(ri RequestIndex) Request {
2241         index := ri / t.chunksPerRegularPiece()
2242         return Request{
2243                 pp.Integer(index),
2244                 t.piece(int(index)).chunkIndexSpec(ri % t.chunksPerRegularPiece()),
2245         }
2246 }
2247
2248 func (t *Torrent) requestIndexFromRequest(r Request) RequestIndex {
2249         return t.pieceRequestIndexOffset(pieceIndex(r.Index)) + uint32(r.Begin/t.chunkSize)
2250 }
2251
2252 func (t *Torrent) pieceRequestIndexOffset(piece pieceIndex) RequestIndex {
2253         return RequestIndex(piece) * t.chunksPerRegularPiece()
2254 }
2255
2256 func (t *Torrent) updateComplete() {
2257         t.Complete.SetBool(t.haveAllPieces())
2258 }