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