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