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