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