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