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