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