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