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