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