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