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