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