]> Sergey Matveev's repositories - btrtrc.git/blob - torrent.go
9aebad9030b9d51c6ead022182adb4f591053536
[btrtrc.git] / torrent.go
1 package torrent
2
3 import (
4         "container/heap"
5         "crypto/sha1"
6         "errors"
7         "fmt"
8         "io"
9         "math"
10         "math/rand"
11         "net"
12         "net/url"
13         "os"
14         "strconv"
15         "sync"
16         "text/tabwriter"
17         "time"
18
19         "github.com/anacrolix/dht"
20         "github.com/anacrolix/log"
21         "github.com/anacrolix/missinggo"
22         "github.com/anacrolix/missinggo/bitmap"
23         "github.com/anacrolix/missinggo/perf"
24         "github.com/anacrolix/missinggo/prioritybitmap"
25         "github.com/anacrolix/missinggo/pubsub"
26         "github.com/anacrolix/missinggo/slices"
27         "github.com/davecgh/go-spew/spew"
28
29         "github.com/anacrolix/torrent/bencode"
30         "github.com/anacrolix/torrent/metainfo"
31         pp "github.com/anacrolix/torrent/peer_protocol"
32         "github.com/anacrolix/torrent/storage"
33         "github.com/anacrolix/torrent/tracker"
34 )
35
36 func (t *Torrent) chunkIndexSpec(chunkIndex pp.Integer, piece pieceIndex) chunkSpec {
37         return chunkIndexSpec(chunkIndex, t.pieceLength(piece), t.chunkSize)
38 }
39
40 type peersKey struct {
41         IPBytes string
42         Port    int
43 }
44
45 // Maintains state of torrent within a Client.
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 bool
54
55         // Determines what chunks to request from peers. 1: Favour higher priority
56         // pieces with some fuzzing to reduce overlaps and wastage across
57         // connections. 2: The fastest connection downloads strictly in order of
58         // priority, while all others adher to their piece inclications. 3:
59         // Requests are strictly by piece priority, and not duplicated until
60         // duplicateRequestTimeout is reached.
61         requestStrategy int
62         // How long to avoid duplicating a pending request.
63         duplicateRequestTimeout time.Duration
64
65         closed   missinggo.Event
66         infoHash metainfo.Hash
67         pieces   []Piece
68         // Values are the piece indices that changed.
69         pieceStateChanges *pubsub.PubSub
70         // The size of chunks to request from peers over the wire. This is
71         // normally 16KiB by convention these days.
72         chunkSize pp.Integer
73         chunkPool *sync.Pool
74         // Total length of the torrent in bytes. Stored because it's not O(1) to
75         // get this from the info dict.
76         length *int64
77
78         // The storage to open when the info dict becomes available.
79         storageOpener *storage.Client
80         // Storage for torrent data.
81         storage *storage.Torrent
82         // Read-locked for using storage, and write-locked for Closing.
83         storageLock sync.RWMutex
84
85         // TODO: Only announce stuff is used?
86         metainfo metainfo.MetaInfo
87
88         // The info dict. nil if we don't have it (yet).
89         info  *metainfo.Info
90         files *[]*File
91
92         // Active peer connections, running message stream loops. TODO: Make this
93         // open (not-closed) connections only.
94         conns               map[*connection]struct{}
95         maxEstablishedConns int
96         // Set of addrs to which we're attempting to connect. Connections are
97         // half-open until all handshakes are completed.
98         halfOpen    map[string]Peer
99         fastestConn *connection
100
101         // Reserve of peers to connect to. A peer can be both here and in the
102         // active connections if were told about the peer after connecting with
103         // them. That encourages us to reconnect to peers that are well known in
104         // the swarm.
105         peers          prioritizedPeers
106         wantPeersEvent missinggo.Event
107         // An announcer for each tracker URL.
108         trackerAnnouncers map[string]*trackerScraper
109         // How many times we've initiated a DHT announce. TODO: Move into stats.
110         numDHTAnnounces int
111
112         // Name used if the info name isn't available. Should be cleared when the
113         // Info does become available.
114         displayName string
115
116         // The bencoded bytes of the info dict. This is actively manipulated if
117         // the info bytes aren't initially available, and we try to fetch them
118         // from peers.
119         metadataBytes []byte
120         // Each element corresponds to the 16KiB metadata pieces. If true, we have
121         // received that piece.
122         metadataCompletedChunks []bool
123         metadataChanged         sync.Cond
124
125         // Set when .Info is obtained.
126         gotMetainfo missinggo.Event
127
128         readers               map[*reader]struct{}
129         readerNowPieces       bitmap.Bitmap
130         readerReadaheadPieces bitmap.Bitmap
131
132         // A cache of pieces we need to get. Calculated from various piece and
133         // file priorities and completion states elsewhere.
134         pendingPieces prioritybitmap.PriorityBitmap
135         // A cache of completed piece indices.
136         completedPieces bitmap.Bitmap
137         // Pieces that need to be hashed.
138         piecesQueuedForHash bitmap.Bitmap
139
140         // A pool of piece priorities []int for assignment to new connections.
141         // These "inclinations" are used to give connections preference for
142         // different pieces.
143         connPieceInclinationPool sync.Pool
144
145         // Count of each request across active connections.
146         pendingRequests map[request]int
147         // The last time we requested a chunk. Deleting the request from any
148         // connection will clear this value.
149         lastRequested map[request]*time.Timer
150 }
151
152 func (t *Torrent) tickleReaders() {
153         t.cl.event.Broadcast()
154 }
155
156 // Returns a channel that is closed when the Torrent is closed.
157 func (t *Torrent) Closed() <-chan struct{} {
158         return t.closed.LockedChan(&t.cl.mu)
159 }
160
161 // KnownSwarm returns the known subset of the peers in the Torrent's swarm, including active,
162 // pending, and half-open peers.
163 func (t *Torrent) KnownSwarm() (ks []Peer) {
164         // Add pending peers to the list
165         t.peers.Each(func(peer Peer) {
166                 ks = append(ks, peer)
167         })
168
169         // Add half-open peers to the list
170         for _, peer := range t.halfOpen {
171                 ks = append(ks, peer)
172         }
173
174         // Add active peers to the list
175         for conn := range t.conns {
176                 host, portString, err := net.SplitHostPort(conn.remoteAddr().String())
177                 if err != nil {
178                         panic(err)
179                 }
180
181                 ip := net.ParseIP(host)
182                 port, err := strconv.Atoi(portString)
183                 if err != nil {
184                         panic(err)
185                 }
186
187                 ks = append(ks, Peer{
188                         Id:     conn.PeerID,
189                         IP:     ip,
190                         Port:   port,
191                         Source: conn.Discovery,
192                         // > If the connection is encrypted, that's certainly enough to set SupportsEncryption.
193                         // > But if we're not connected to them with an encrypted connection, I couldn't say
194                         // > what's appropriate. We can carry forward the SupportsEncryption value as we
195                         // > received it from trackers/DHT/PEX, or just use the encryption state for the
196                         // > connection. It's probably easiest to do the latter for now.
197                         // https://github.com/anacrolix/torrent/pull/188
198                         SupportsEncryption: conn.headerEncrypted,
199                 })
200         }
201
202         return
203 }
204
205 func (t *Torrent) setChunkSize(size pp.Integer) {
206         t.chunkSize = size
207         t.chunkPool = &sync.Pool{
208                 New: func() interface{} {
209                         b := make([]byte, size)
210                         return &b
211                 },
212         }
213 }
214
215 func (t *Torrent) setDisplayName(dn string) {
216         if t.haveInfo() {
217                 return
218         }
219         t.displayName = dn
220 }
221
222 func (t *Torrent) pieceComplete(piece pieceIndex) bool {
223         return t.completedPieces.Get(bitmap.BitIndex(piece))
224 }
225
226 func (t *Torrent) pieceCompleteUncached(piece pieceIndex) storage.Completion {
227         return t.pieces[piece].Storage().Completion()
228 }
229
230 // There's a connection to that address already.
231 func (t *Torrent) addrActive(addr string) bool {
232         if _, ok := t.halfOpen[addr]; ok {
233                 return true
234         }
235         for c := range t.conns {
236                 ra := c.remoteAddr()
237                 if ra == nil {
238                         continue
239                 }
240                 if ra.String() == addr {
241                         return true
242                 }
243         }
244         return false
245 }
246
247 func (t *Torrent) unclosedConnsAsSlice() (ret []*connection) {
248         ret = make([]*connection, 0, len(t.conns))
249         for c := range t.conns {
250                 if !c.closed.IsSet() {
251                         ret = append(ret, c)
252                 }
253         }
254         return
255 }
256
257 func (t *Torrent) addPeer(p Peer) {
258         cl := t.cl
259         peersAddedBySource.Add(string(p.Source), 1)
260         if t.closed.IsSet() {
261                 return
262         }
263         if cl.badPeerIPPort(p.IP, p.Port) {
264                 torrent.Add("peers not added because of bad addr", 1)
265                 return
266         }
267         if t.peers.Add(p) {
268                 torrent.Add("peers replaced", 1)
269         }
270         t.openNewConns()
271         for t.peers.Len() > cl.config.TorrentPeersHighWater {
272                 _, ok := t.peers.DeleteMin()
273                 if ok {
274                         torrent.Add("excess reserve peers discarded", 1)
275                 }
276         }
277 }
278
279 func (t *Torrent) invalidateMetadata() {
280         for i := range t.metadataCompletedChunks {
281                 t.metadataCompletedChunks[i] = false
282         }
283         t.info = nil
284 }
285
286 func (t *Torrent) saveMetadataPiece(index int, data []byte) {
287         if t.haveInfo() {
288                 return
289         }
290         if index >= len(t.metadataCompletedChunks) {
291                 log.Printf("%s: ignoring metadata piece %d", t, index)
292                 return
293         }
294         copy(t.metadataBytes[(1<<14)*index:], data)
295         t.metadataCompletedChunks[index] = true
296 }
297
298 func (t *Torrent) metadataPieceCount() int {
299         return (len(t.metadataBytes) + (1 << 14) - 1) / (1 << 14)
300 }
301
302 func (t *Torrent) haveMetadataPiece(piece int) bool {
303         if t.haveInfo() {
304                 return (1<<14)*piece < len(t.metadataBytes)
305         } else {
306                 return piece < len(t.metadataCompletedChunks) && t.metadataCompletedChunks[piece]
307         }
308 }
309
310 func (t *Torrent) metadataSizeKnown() bool {
311         return t.metadataBytes != nil
312 }
313
314 func (t *Torrent) metadataSize() int {
315         return len(t.metadataBytes)
316 }
317
318 func infoPieceHashes(info *metainfo.Info) (ret []string) {
319         for i := 0; i < len(info.Pieces); i += sha1.Size {
320                 ret = append(ret, string(info.Pieces[i:i+sha1.Size]))
321         }
322         return
323 }
324
325 func (t *Torrent) makePieces() {
326         hashes := infoPieceHashes(t.info)
327         t.pieces = make([]Piece, len(hashes), len(hashes))
328         for i, hash := range hashes {
329                 piece := &t.pieces[i]
330                 piece.t = t
331                 piece.index = pieceIndex(i)
332                 piece.noPendingWrites.L = &piece.pendingWritesMutex
333                 missinggo.CopyExact(piece.hash[:], hash)
334                 files := *t.files
335                 beginFile := pieceFirstFileIndex(piece.torrentBeginOffset(), files)
336                 endFile := pieceEndFileIndex(piece.torrentEndOffset(), files)
337                 piece.files = files[beginFile:endFile]
338         }
339 }
340
341 // Returns the index of the first file containing the piece. files must be
342 // ordered by offset.
343 func pieceFirstFileIndex(pieceOffset int64, files []*File) int {
344         for i, f := range files {
345                 if f.offset+f.length > pieceOffset {
346                         return i
347                 }
348         }
349         return 0
350 }
351
352 // Returns the index after the last file containing the piece. files must be
353 // ordered by offset.
354 func pieceEndFileIndex(pieceEndOffset int64, files []*File) int {
355         for i, f := range files {
356                 if f.offset+f.length >= pieceEndOffset {
357                         return i + 1
358                 }
359         }
360         return 0
361 }
362
363 func (t *Torrent) cacheLength() {
364         var l int64
365         for _, f := range t.info.UpvertedFiles() {
366                 l += f.Length
367         }
368         t.length = &l
369 }
370
371 func (t *Torrent) setInfo(info *metainfo.Info) error {
372         if err := validateInfo(info); err != nil {
373                 return fmt.Errorf("bad info: %s", err)
374         }
375         if t.storageOpener != nil {
376                 var err error
377                 t.storage, err = t.storageOpener.OpenTorrent(info, t.infoHash)
378                 if err != nil {
379                         return fmt.Errorf("error opening torrent storage: %s", err)
380                 }
381         }
382         t.info = info
383         t.displayName = "" // Save a few bytes lol.
384         t.initFiles()
385         t.cacheLength()
386         t.makePieces()
387         return nil
388 }
389
390 func (t *Torrent) onSetInfo() {
391         for conn := range t.conns {
392                 if err := conn.setNumPieces(t.numPieces()); err != nil {
393                         log.Printf("closing connection: %s", err)
394                         conn.Close()
395                 }
396         }
397         for i := range t.pieces {
398                 t.updatePieceCompletion(pieceIndex(i))
399                 p := &t.pieces[i]
400                 if !p.storageCompletionOk {
401                         // log.Printf("piece %s completion unknown, queueing check", p)
402                         t.queuePieceCheck(pieceIndex(i))
403                 }
404         }
405         t.cl.event.Broadcast()
406         t.gotMetainfo.Set()
407         t.updateWantPeersEvent()
408         t.pendingRequests = make(map[request]int)
409         t.lastRequested = make(map[request]*time.Timer)
410 }
411
412 // Called when metadata for a torrent becomes available.
413 func (t *Torrent) setInfoBytes(b []byte) error {
414         if metainfo.HashBytes(b) != t.infoHash {
415                 return errors.New("info bytes have wrong hash")
416         }
417         var info metainfo.Info
418         if err := bencode.Unmarshal(b, &info); err != nil {
419                 return fmt.Errorf("error unmarshalling info bytes: %s", err)
420         }
421         if err := t.setInfo(&info); err != nil {
422                 return err
423         }
424         t.metadataBytes = b
425         t.metadataCompletedChunks = nil
426         t.onSetInfo()
427         return nil
428 }
429
430 func (t *Torrent) haveAllMetadataPieces() bool {
431         if t.haveInfo() {
432                 return true
433         }
434         if t.metadataCompletedChunks == nil {
435                 return false
436         }
437         for _, have := range t.metadataCompletedChunks {
438                 if !have {
439                         return false
440                 }
441         }
442         return true
443 }
444
445 // TODO: Propagate errors to disconnect peer.
446 func (t *Torrent) setMetadataSize(bytes int) (err error) {
447         if t.haveInfo() {
448                 // We already know the correct metadata size.
449                 return
450         }
451         if bytes <= 0 || bytes > 10000000 { // 10MB, pulled from my ass.
452                 return errors.New("bad size")
453         }
454         if t.metadataBytes != nil && len(t.metadataBytes) == int(bytes) {
455                 return
456         }
457         t.metadataBytes = make([]byte, bytes)
458         t.metadataCompletedChunks = make([]bool, (bytes+(1<<14)-1)/(1<<14))
459         t.metadataChanged.Broadcast()
460         for c := range t.conns {
461                 c.requestPendingMetadata()
462         }
463         return
464 }
465
466 // The current working name for the torrent. Either the name in the info dict,
467 // or a display name given such as by the dn value in a magnet link, or "".
468 func (t *Torrent) name() string {
469         if t.haveInfo() {
470                 return t.info.Name
471         }
472         return t.displayName
473 }
474
475 func (t *Torrent) pieceState(index pieceIndex) (ret PieceState) {
476         p := &t.pieces[index]
477         ret.Priority = t.piecePriority(index)
478         ret.Completion = p.completion()
479         if p.queuedForHash() || p.hashing {
480                 ret.Checking = true
481         }
482         if !ret.Complete && t.piecePartiallyDownloaded(index) {
483                 ret.Partial = true
484         }
485         return
486 }
487
488 func (t *Torrent) metadataPieceSize(piece int) int {
489         return metadataPieceSize(len(t.metadataBytes), piece)
490 }
491
492 func (t *Torrent) newMetadataExtensionMessage(c *connection, msgType int, piece int, data []byte) pp.Message {
493         d := map[string]int{
494                 "msg_type": msgType,
495                 "piece":    piece,
496         }
497         if data != nil {
498                 d["total_size"] = len(t.metadataBytes)
499         }
500         p := bencode.MustMarshal(d)
501         return pp.Message{
502                 Type:            pp.Extended,
503                 ExtendedID:      c.PeerExtensionIDs[pp.ExtensionNameMetadata],
504                 ExtendedPayload: append(p, data...),
505         }
506 }
507
508 func (t *Torrent) pieceStateRuns() (ret []PieceStateRun) {
509         rle := missinggo.NewRunLengthEncoder(func(el interface{}, count uint64) {
510                 ret = append(ret, PieceStateRun{
511                         PieceState: el.(PieceState),
512                         Length:     int(count),
513                 })
514         })
515         for index := range t.pieces {
516                 rle.Append(t.pieceState(pieceIndex(index)), 1)
517         }
518         rle.Flush()
519         return
520 }
521
522 // Produces a small string representing a PieceStateRun.
523 func pieceStateRunStatusChars(psr PieceStateRun) (ret string) {
524         ret = fmt.Sprintf("%d", psr.Length)
525         ret += func() string {
526                 switch psr.Priority {
527                 case PiecePriorityNext:
528                         return "N"
529                 case PiecePriorityNormal:
530                         return "."
531                 case PiecePriorityReadahead:
532                         return "R"
533                 case PiecePriorityNow:
534                         return "!"
535                 case PiecePriorityHigh:
536                         return "H"
537                 default:
538                         return ""
539                 }
540         }()
541         if psr.Checking {
542                 ret += "H"
543         }
544         if psr.Partial {
545                 ret += "P"
546         }
547         if psr.Complete {
548                 ret += "C"
549         }
550         if !psr.Ok {
551                 ret += "?"
552         }
553         return
554 }
555
556 func (t *Torrent) writeStatus(w io.Writer) {
557         fmt.Fprintf(w, "Infohash: %s\n", t.infoHash.HexString())
558         fmt.Fprintf(w, "Metadata length: %d\n", t.metadataSize())
559         if !t.haveInfo() {
560                 fmt.Fprintf(w, "Metadata have: ")
561                 for _, h := range t.metadataCompletedChunks {
562                         fmt.Fprintf(w, "%c", func() rune {
563                                 if h {
564                                         return 'H'
565                                 } else {
566                                         return '.'
567                                 }
568                         }())
569                 }
570                 fmt.Fprintln(w)
571         }
572         fmt.Fprintf(w, "Piece length: %s\n", func() string {
573                 if t.haveInfo() {
574                         return fmt.Sprint(t.usualPieceSize())
575                 } else {
576                         return "?"
577                 }
578         }())
579         if t.info != nil {
580                 fmt.Fprintf(w, "Num Pieces: %d (%d completed)\n", t.numPieces(), t.numPiecesCompleted())
581                 fmt.Fprint(w, "Piece States:")
582                 for _, psr := range t.pieceStateRuns() {
583                         w.Write([]byte(" "))
584                         w.Write([]byte(pieceStateRunStatusChars(psr)))
585                 }
586                 fmt.Fprintln(w)
587         }
588         fmt.Fprintf(w, "Reader Pieces:")
589         t.forReaderOffsetPieces(func(begin, end pieceIndex) (again bool) {
590                 fmt.Fprintf(w, " %d:%d", begin, end)
591                 return true
592         })
593         fmt.Fprintln(w)
594
595         fmt.Fprintf(w, "Enabled trackers:\n")
596         func() {
597                 tw := tabwriter.NewWriter(w, 0, 0, 2, ' ', 0)
598                 fmt.Fprintf(tw, "    URL\tNext announce\tLast announce\n")
599                 for _, ta := range slices.Sort(slices.FromMapElems(t.trackerAnnouncers), func(l, r *trackerScraper) bool {
600                         return l.u.String() < r.u.String()
601                 }).([]*trackerScraper) {
602                         fmt.Fprintf(tw, "    %s\n", ta.statusLine())
603                 }
604                 tw.Flush()
605         }()
606
607         fmt.Fprintf(w, "DHT Announces: %d\n", t.numDHTAnnounces)
608
609         spew.NewDefaultConfig()
610         spew.Fdump(w, t.statsLocked())
611
612         conns := t.connsAsSlice()
613         slices.Sort(conns, worseConn)
614         for i, c := range conns {
615                 fmt.Fprintf(w, "%2d. ", i+1)
616                 c.WriteStatus(w, t)
617         }
618 }
619
620 func (t *Torrent) haveInfo() bool {
621         return t.info != nil
622 }
623
624 // Returns a run-time generated MetaInfo that includes the info bytes and
625 // announce-list as currently known to the client.
626 func (t *Torrent) newMetaInfo() metainfo.MetaInfo {
627         return metainfo.MetaInfo{
628                 CreationDate: time.Now().Unix(),
629                 Comment:      "dynamic metainfo from client",
630                 CreatedBy:    "go.torrent",
631                 AnnounceList: t.metainfo.UpvertedAnnounceList(),
632                 InfoBytes: func() []byte {
633                         if t.haveInfo() {
634                                 return t.metadataBytes
635                         } else {
636                                 return nil
637                         }
638                 }(),
639         }
640 }
641
642 func (t *Torrent) BytesMissing() int64 {
643         t.mu().RLock()
644         defer t.mu().RUnlock()
645         return t.bytesMissingLocked()
646 }
647
648 func (t *Torrent) bytesMissingLocked() int64 {
649         return t.bytesLeft()
650 }
651
652 func (t *Torrent) bytesLeft() (left int64) {
653         bitmap.Flip(t.completedPieces, 0, bitmap.BitIndex(t.numPieces())).IterTyped(func(piece int) bool {
654                 p := &t.pieces[piece]
655                 left += int64(p.length() - p.numDirtyBytes())
656                 return true
657         })
658         return
659 }
660
661 // Bytes left to give in tracker announces.
662 func (t *Torrent) bytesLeftAnnounce() uint64 {
663         if t.haveInfo() {
664                 return uint64(t.bytesLeft())
665         } else {
666                 return math.MaxUint64
667         }
668 }
669
670 func (t *Torrent) piecePartiallyDownloaded(piece pieceIndex) bool {
671         if t.pieceComplete(piece) {
672                 return false
673         }
674         if t.pieceAllDirty(piece) {
675                 return false
676         }
677         return t.pieces[piece].hasDirtyChunks()
678 }
679
680 func (t *Torrent) usualPieceSize() int {
681         return int(t.info.PieceLength)
682 }
683
684 func (t *Torrent) numPieces() pieceIndex {
685         return pieceIndex(t.info.NumPieces())
686 }
687
688 func (t *Torrent) numPiecesCompleted() (num int) {
689         return t.completedPieces.Len()
690 }
691
692 func (t *Torrent) close() (err error) {
693         t.closed.Set()
694         t.tickleReaders()
695         if t.storage != nil {
696                 t.storageLock.Lock()
697                 t.storage.Close()
698                 t.storageLock.Unlock()
699         }
700         for conn := range t.conns {
701                 conn.Close()
702         }
703         t.cl.event.Broadcast()
704         t.pieceStateChanges.Close()
705         t.updateWantPeersEvent()
706         return
707 }
708
709 func (t *Torrent) requestOffset(r request) int64 {
710         return torrentRequestOffset(*t.length, int64(t.usualPieceSize()), r)
711 }
712
713 // Return the request that would include the given offset into the torrent
714 // data. Returns !ok if there is no such request.
715 func (t *Torrent) offsetRequest(off int64) (req request, ok bool) {
716         return torrentOffsetRequest(*t.length, t.info.PieceLength, int64(t.chunkSize), off)
717 }
718
719 func (t *Torrent) writeChunk(piece int, begin int64, data []byte) (err error) {
720         defer perf.ScopeTimerErr(&err)()
721         n, err := t.pieces[piece].Storage().WriteAt(data, begin)
722         if err == nil && n != len(data) {
723                 err = io.ErrShortWrite
724         }
725         return
726 }
727
728 func (t *Torrent) bitfield() (bf []bool) {
729         bf = make([]bool, t.numPieces())
730         t.completedPieces.IterTyped(func(piece int) (again bool) {
731                 bf[piece] = true
732                 return true
733         })
734         return
735 }
736
737 func (t *Torrent) pieceNumChunks(piece pieceIndex) pp.Integer {
738         return (t.pieceLength(piece) + t.chunkSize - 1) / t.chunkSize
739 }
740
741 func (t *Torrent) pendAllChunkSpecs(pieceIndex pieceIndex) {
742         t.pieces[pieceIndex].dirtyChunks.Clear()
743 }
744
745 func (t *Torrent) pieceLength(piece pieceIndex) pp.Integer {
746         if t.info.PieceLength == 0 {
747                 // There will be no variance amongst pieces. Only pain.
748                 return 0
749         }
750         if piece == t.numPieces()-1 {
751                 ret := pp.Integer(*t.length % t.info.PieceLength)
752                 if ret != 0 {
753                         return ret
754                 }
755         }
756         return pp.Integer(t.info.PieceLength)
757 }
758
759 func (t *Torrent) hashPiece(piece pieceIndex) (ret metainfo.Hash) {
760         hash := pieceHash.New()
761         p := &t.pieces[piece]
762         p.waitNoPendingWrites()
763         ip := t.info.Piece(int(piece))
764         pl := ip.Length()
765         n, err := io.Copy(hash, io.NewSectionReader(t.pieces[piece].Storage(), 0, pl))
766         if n == pl {
767                 missinggo.CopyExact(&ret, hash.Sum(nil))
768                 return
769         }
770         if err != io.ErrUnexpectedEOF && !os.IsNotExist(err) {
771                 log.Printf("unexpected error hashing piece with %T: %s", t.storage.TorrentImpl, err)
772         }
773         return
774 }
775
776 func (t *Torrent) haveAnyPieces() bool {
777         return t.completedPieces.Len() != 0
778 }
779
780 func (t *Torrent) haveAllPieces() bool {
781         if !t.haveInfo() {
782                 return false
783         }
784         return t.completedPieces.Len() == bitmap.BitIndex(t.numPieces())
785 }
786
787 func (t *Torrent) havePiece(index pieceIndex) bool {
788         return t.haveInfo() && t.pieceComplete(index)
789 }
790
791 func (t *Torrent) haveChunk(r request) (ret bool) {
792         // defer func() {
793         //      log.Println("have chunk", r, ret)
794         // }()
795         if !t.haveInfo() {
796                 return false
797         }
798         if t.pieceComplete(pieceIndex(r.Index)) {
799                 return true
800         }
801         p := &t.pieces[r.Index]
802         return !p.pendingChunk(r.chunkSpec, t.chunkSize)
803 }
804
805 func chunkIndex(cs chunkSpec, chunkSize pp.Integer) int {
806         return int(cs.Begin / chunkSize)
807 }
808
809 func (t *Torrent) wantPiece(r request) bool {
810         if !t.wantPieceIndex(pieceIndex(r.Index)) {
811                 return false
812         }
813         if t.pieces[r.Index].pendingChunk(r.chunkSpec, t.chunkSize) {
814                 return true
815         }
816         // TODO: What about pieces that were wanted, but aren't now, and aren't
817         // completed either? That used to be done here.
818         return false
819 }
820
821 func (t *Torrent) wantPieceIndex(index pieceIndex) bool {
822         if !t.haveInfo() {
823                 return false
824         }
825         if index < 0 || index >= t.numPieces() {
826                 return false
827         }
828         p := &t.pieces[index]
829         if p.queuedForHash() {
830                 return false
831         }
832         if p.hashing {
833                 return false
834         }
835         if t.pieceComplete(index) {
836                 return false
837         }
838         if t.pendingPieces.Contains(bitmap.BitIndex(index)) {
839                 return true
840         }
841         // log.Printf("piece %d not pending", index)
842         return !t.forReaderOffsetPieces(func(begin, end pieceIndex) bool {
843                 return index < begin || index >= end
844         })
845 }
846
847 // The worst connection is one that hasn't been sent, or sent anything useful
848 // for the longest. A bad connection is one that usually sends us unwanted
849 // pieces, or has been in worser half of the established connections for more
850 // than a minute.
851 func (t *Torrent) worstBadConn() *connection {
852         wcs := worseConnSlice{t.unclosedConnsAsSlice()}
853         heap.Init(&wcs)
854         for wcs.Len() != 0 {
855                 c := heap.Pop(&wcs).(*connection)
856                 if c.stats.ChunksReadWasted.Int64() >= 6 && c.stats.ChunksReadWasted.Int64() > c.stats.ChunksReadUseful.Int64() {
857                         return c
858                 }
859                 // If the connection is in the worst half of the established
860                 // connection quota and is older than a minute.
861                 if wcs.Len() >= (t.maxEstablishedConns+1)/2 {
862                         // Give connections 1 minute to prove themselves.
863                         if time.Since(c.completedHandshake) > time.Minute {
864                                 return c
865                         }
866                 }
867         }
868         return nil
869 }
870
871 type PieceStateChange struct {
872         Index int
873         PieceState
874 }
875
876 func (t *Torrent) publishPieceChange(piece pieceIndex) {
877         cur := t.pieceState(piece)
878         p := &t.pieces[piece]
879         if cur != p.publicPieceState {
880                 p.publicPieceState = cur
881                 t.pieceStateChanges.Publish(PieceStateChange{
882                         int(piece),
883                         cur,
884                 })
885         }
886 }
887
888 func (t *Torrent) pieceNumPendingChunks(piece pieceIndex) pp.Integer {
889         if t.pieceComplete(piece) {
890                 return 0
891         }
892         return t.pieceNumChunks(piece) - t.pieces[piece].numDirtyChunks()
893 }
894
895 func (t *Torrent) pieceAllDirty(piece pieceIndex) bool {
896         return t.pieces[piece].dirtyChunks.Len() == int(t.pieceNumChunks(piece))
897 }
898
899 func (t *Torrent) readersChanged() {
900         t.updateReaderPieces()
901         t.updateAllPiecePriorities()
902 }
903
904 func (t *Torrent) updateReaderPieces() {
905         t.readerNowPieces, t.readerReadaheadPieces = t.readerPiecePriorities()
906 }
907
908 func (t *Torrent) readerPosChanged(from, to pieceRange) {
909         if from == to {
910                 return
911         }
912         t.updateReaderPieces()
913         // Order the ranges, high and low.
914         l, h := from, to
915         if l.begin > h.begin {
916                 l, h = h, l
917         }
918         if l.end < h.begin {
919                 // Two distinct ranges.
920                 t.updatePiecePriorities(l.begin, l.end)
921                 t.updatePiecePriorities(h.begin, h.end)
922         } else {
923                 // Ranges overlap.
924                 end := l.end
925                 if h.end > end {
926                         end = h.end
927                 }
928                 t.updatePiecePriorities(l.begin, end)
929         }
930 }
931
932 func (t *Torrent) maybeNewConns() {
933         // Tickle the accept routine.
934         t.cl.event.Broadcast()
935         t.openNewConns()
936 }
937
938 func (t *Torrent) piecePriorityChanged(piece pieceIndex) {
939         // log.Printf("piece %d priority changed", piece)
940         for c := range t.conns {
941                 if c.updatePiecePriority(piece) {
942                         // log.Print("conn piece priority changed")
943                         c.updateRequests()
944                 }
945         }
946         t.maybeNewConns()
947         t.publishPieceChange(piece)
948 }
949
950 func (t *Torrent) updatePiecePriority(piece pieceIndex) {
951         p := &t.pieces[piece]
952         newPrio := p.uncachedPriority()
953         // log.Printf("torrent %p: piece %d: uncached priority: %v", t, piece, newPrio)
954         if newPrio == PiecePriorityNone {
955                 if !t.pendingPieces.Remove(bitmap.BitIndex(piece)) {
956                         return
957                 }
958         } else {
959                 if !t.pendingPieces.Set(bitmap.BitIndex(piece), newPrio.BitmapPriority()) {
960                         return
961                 }
962         }
963         t.piecePriorityChanged(piece)
964 }
965
966 func (t *Torrent) updateAllPiecePriorities() {
967         t.updatePiecePriorities(0, t.numPieces())
968 }
969
970 // Update all piece priorities in one hit. This function should have the same
971 // output as updatePiecePriority, but across all pieces.
972 func (t *Torrent) updatePiecePriorities(begin, end pieceIndex) {
973         for i := begin; i < end; i++ {
974                 t.updatePiecePriority(i)
975         }
976 }
977
978 // Returns the range of pieces [begin, end) that contains the extent of bytes.
979 func (t *Torrent) byteRegionPieces(off, size int64) (begin, end pieceIndex) {
980         if off >= *t.length {
981                 return
982         }
983         if off < 0 {
984                 size += off
985                 off = 0
986         }
987         if size <= 0 {
988                 return
989         }
990         begin = pieceIndex(off / t.info.PieceLength)
991         end = pieceIndex((off + size + t.info.PieceLength - 1) / t.info.PieceLength)
992         if end > pieceIndex(t.info.NumPieces()) {
993                 end = pieceIndex(t.info.NumPieces())
994         }
995         return
996 }
997
998 // Returns true if all iterations complete without breaking. Returns the read
999 // regions for all readers. The reader regions should not be merged as some
1000 // callers depend on this method to enumerate readers.
1001 func (t *Torrent) forReaderOffsetPieces(f func(begin, end pieceIndex) (more bool)) (all bool) {
1002         for r := range t.readers {
1003                 p := r.pieces
1004                 if p.begin >= p.end {
1005                         continue
1006                 }
1007                 if !f(p.begin, p.end) {
1008                         return false
1009                 }
1010         }
1011         return true
1012 }
1013
1014 func (t *Torrent) piecePriority(piece pieceIndex) piecePriority {
1015         prio, ok := t.pendingPieces.GetPriority(bitmap.BitIndex(piece))
1016         if !ok {
1017                 return PiecePriorityNone
1018         }
1019         if prio > 0 {
1020                 panic(prio)
1021         }
1022         ret := piecePriority(-prio)
1023         if ret == PiecePriorityNone {
1024                 panic(piece)
1025         }
1026         return ret
1027 }
1028
1029 func (t *Torrent) pendRequest(req request) {
1030         ci := chunkIndex(req.chunkSpec, t.chunkSize)
1031         t.pieces[req.Index].pendChunkIndex(ci)
1032 }
1033
1034 func (t *Torrent) pieceCompletionChanged(piece pieceIndex) {
1035         log.Call().Add("piece", piece).AddValue(debugLogValue).Log(t.logger)
1036         t.cl.event.Broadcast()
1037         if t.pieceComplete(piece) {
1038                 t.onPieceCompleted(piece)
1039         } else {
1040                 t.onIncompletePiece(piece)
1041         }
1042         t.updatePiecePriority(piece)
1043 }
1044
1045 func (t *Torrent) numReceivedConns() (ret int) {
1046         for c := range t.conns {
1047                 if c.Discovery == peerSourceIncoming {
1048                         ret++
1049                 }
1050         }
1051         return
1052 }
1053
1054 func (t *Torrent) maxHalfOpen() int {
1055         // Note that if we somehow exceed the maximum established conns, we want
1056         // the negative value to have an effect.
1057         establishedHeadroom := int64(t.maxEstablishedConns - len(t.conns))
1058         extraIncoming := int64(t.numReceivedConns() - t.maxEstablishedConns/2)
1059         // We want to allow some experimentation with new peers, and to try to
1060         // upset an oversupply of received connections.
1061         return int(min(max(5, extraIncoming)+establishedHeadroom, int64(t.cl.config.HalfOpenConnsPerTorrent)))
1062 }
1063
1064 func (t *Torrent) openNewConns() {
1065         defer t.updateWantPeersEvent()
1066         for t.peers.Len() != 0 {
1067                 if !t.wantConns() {
1068                         return
1069                 }
1070                 if len(t.halfOpen) >= t.maxHalfOpen() {
1071                         return
1072                 }
1073                 p := t.peers.PopMax()
1074                 t.initiateConn(p)
1075         }
1076 }
1077
1078 func (t *Torrent) getConnPieceInclination() []int {
1079         _ret := t.connPieceInclinationPool.Get()
1080         if _ret == nil {
1081                 pieceInclinationsNew.Add(1)
1082                 return rand.Perm(int(t.numPieces()))
1083         }
1084         pieceInclinationsReused.Add(1)
1085         return *_ret.(*[]int)
1086 }
1087
1088 func (t *Torrent) putPieceInclination(pi []int) {
1089         t.connPieceInclinationPool.Put(&pi)
1090         pieceInclinationsPut.Add(1)
1091 }
1092
1093 func (t *Torrent) updatePieceCompletion(piece pieceIndex) {
1094         pcu := t.pieceCompleteUncached(piece)
1095         p := &t.pieces[piece]
1096         changed := t.completedPieces.Get(bitmap.BitIndex(piece)) != pcu.Complete || p.storageCompletionOk != pcu.Ok
1097         log.Fmsg("piece %d completion: %v", piece, pcu.Ok).AddValue(debugLogValue).Log(t.logger)
1098         p.storageCompletionOk = pcu.Ok
1099         t.completedPieces.Set(bitmap.BitIndex(piece), pcu.Complete)
1100         t.tickleReaders()
1101         // log.Printf("piece %d uncached completion: %v", piece, pcu.Complete)
1102         // log.Printf("piece %d changed: %v", piece, changed)
1103         if changed {
1104                 t.pieceCompletionChanged(piece)
1105         }
1106 }
1107
1108 // Non-blocking read. Client lock is not required.
1109 func (t *Torrent) readAt(b []byte, off int64) (n int, err error) {
1110         p := &t.pieces[off/t.info.PieceLength]
1111         p.waitNoPendingWrites()
1112         return p.Storage().ReadAt(b, off-p.Info().Offset())
1113 }
1114
1115 func (t *Torrent) updateAllPieceCompletions() {
1116         for i := pieceIndex(0); i < t.numPieces(); i++ {
1117                 t.updatePieceCompletion(i)
1118         }
1119 }
1120
1121 // Returns an error if the metadata was completed, but couldn't be set for
1122 // some reason. Blame it on the last peer to contribute.
1123 func (t *Torrent) maybeCompleteMetadata() error {
1124         if t.haveInfo() {
1125                 // Nothing to do.
1126                 return nil
1127         }
1128         if !t.haveAllMetadataPieces() {
1129                 // Don't have enough metadata pieces.
1130                 return nil
1131         }
1132         err := t.setInfoBytes(t.metadataBytes)
1133         if err != nil {
1134                 t.invalidateMetadata()
1135                 return fmt.Errorf("error setting info bytes: %s", err)
1136         }
1137         if t.cl.config.Debug {
1138                 log.Printf("%s: got metadata from peers", t)
1139         }
1140         return nil
1141 }
1142
1143 func (t *Torrent) readerPieces() (ret bitmap.Bitmap) {
1144         t.forReaderOffsetPieces(func(begin, end pieceIndex) bool {
1145                 ret.AddRange(bitmap.BitIndex(begin), bitmap.BitIndex(end))
1146                 return true
1147         })
1148         return
1149 }
1150
1151 func (t *Torrent) readerPiecePriorities() (now, readahead bitmap.Bitmap) {
1152         t.forReaderOffsetPieces(func(begin, end pieceIndex) bool {
1153                 if end > begin {
1154                         now.Add(bitmap.BitIndex(begin))
1155                         readahead.AddRange(bitmap.BitIndex(begin)+1, bitmap.BitIndex(end))
1156                 }
1157                 return true
1158         })
1159         return
1160 }
1161
1162 func (t *Torrent) needData() bool {
1163         if t.closed.IsSet() {
1164                 return false
1165         }
1166         if !t.haveInfo() {
1167                 return true
1168         }
1169         return t.pendingPieces.Len() != 0
1170 }
1171
1172 func appendMissingStrings(old, new []string) (ret []string) {
1173         ret = old
1174 new:
1175         for _, n := range new {
1176                 for _, o := range old {
1177                         if o == n {
1178                                 continue new
1179                         }
1180                 }
1181                 ret = append(ret, n)
1182         }
1183         return
1184 }
1185
1186 func appendMissingTrackerTiers(existing [][]string, minNumTiers int) (ret [][]string) {
1187         ret = existing
1188         for minNumTiers > len(ret) {
1189                 ret = append(ret, nil)
1190         }
1191         return
1192 }
1193
1194 func (t *Torrent) addTrackers(announceList [][]string) {
1195         fullAnnounceList := &t.metainfo.AnnounceList
1196         t.metainfo.AnnounceList = appendMissingTrackerTiers(*fullAnnounceList, len(announceList))
1197         for tierIndex, trackerURLs := range announceList {
1198                 (*fullAnnounceList)[tierIndex] = appendMissingStrings((*fullAnnounceList)[tierIndex], trackerURLs)
1199         }
1200         t.startMissingTrackerScrapers()
1201         t.updateWantPeersEvent()
1202 }
1203
1204 // Don't call this before the info is available.
1205 func (t *Torrent) bytesCompleted() int64 {
1206         if !t.haveInfo() {
1207                 return 0
1208         }
1209         return t.info.TotalLength() - t.bytesLeft()
1210 }
1211
1212 func (t *Torrent) SetInfoBytes(b []byte) (err error) {
1213         t.cl.mu.Lock()
1214         defer t.cl.mu.Unlock()
1215         return t.setInfoBytes(b)
1216 }
1217
1218 // Returns true if connection is removed from torrent.Conns.
1219 func (t *Torrent) deleteConnection(c *connection) (ret bool) {
1220         if !c.closed.IsSet() {
1221                 panic("connection is not closed")
1222                 // There are behaviours prevented by the closed state that will fail
1223                 // if the connection has been deleted.
1224         }
1225         _, ret = t.conns[c]
1226         delete(t.conns, c)
1227         torrent.Add("deleted connections", 1)
1228         c.deleteAllRequests()
1229         if len(t.conns) == 0 {
1230                 t.assertNoPendingRequests()
1231         }
1232         return
1233 }
1234
1235 func (t *Torrent) assertNoPendingRequests() {
1236         if len(t.pendingRequests) != 0 {
1237                 panic(t.pendingRequests)
1238         }
1239         if len(t.lastRequested) != 0 {
1240                 panic(t.lastRequested)
1241         }
1242 }
1243
1244 func (t *Torrent) dropConnection(c *connection) {
1245         t.cl.event.Broadcast()
1246         c.Close()
1247         if t.deleteConnection(c) {
1248                 t.openNewConns()
1249         }
1250 }
1251
1252 func (t *Torrent) wantPeers() bool {
1253         if t.closed.IsSet() {
1254                 return false
1255         }
1256         if t.peers.Len() > t.cl.config.TorrentPeersLowWater {
1257                 return false
1258         }
1259         return t.needData() || t.seeding()
1260 }
1261
1262 func (t *Torrent) updateWantPeersEvent() {
1263         if t.wantPeers() {
1264                 t.wantPeersEvent.Set()
1265         } else {
1266                 t.wantPeersEvent.Clear()
1267         }
1268 }
1269
1270 // Returns whether the client should make effort to seed the torrent.
1271 func (t *Torrent) seeding() bool {
1272         cl := t.cl
1273         if t.closed.IsSet() {
1274                 return false
1275         }
1276         if cl.config.NoUpload {
1277                 return false
1278         }
1279         if !cl.config.Seed {
1280                 return false
1281         }
1282         if cl.config.DisableAggressiveUpload && t.needData() {
1283                 return false
1284         }
1285         return true
1286 }
1287
1288 func (t *Torrent) startScrapingTracker(_url string) {
1289         if _url == "" {
1290                 return
1291         }
1292         u, err := url.Parse(_url)
1293         if err != nil {
1294                 log.Str("error parsing tracker url").AddValues("url", _url).Log(t.logger)
1295                 // TODO: Handle urls with leading '*', some kind of silly uTorrent
1296                 // convention?
1297                 return
1298         }
1299         if u.Scheme == "udp" {
1300                 u.Scheme = "udp4"
1301                 t.startScrapingTracker(u.String())
1302                 u.Scheme = "udp6"
1303                 t.startScrapingTracker(u.String())
1304                 return
1305         }
1306         if u.Scheme == "udp4" && (t.cl.config.DisableIPv4Peers || t.cl.config.DisableIPv4) {
1307                 return
1308         }
1309         if u.Scheme == "udp6" && t.cl.config.DisableIPv6 {
1310                 return
1311         }
1312         if _, ok := t.trackerAnnouncers[_url]; ok {
1313                 return
1314         }
1315         newAnnouncer := &trackerScraper{
1316                 u: *u,
1317                 t: t,
1318         }
1319         if t.trackerAnnouncers == nil {
1320                 t.trackerAnnouncers = make(map[string]*trackerScraper)
1321         }
1322         t.trackerAnnouncers[_url] = newAnnouncer
1323         go newAnnouncer.Run()
1324 }
1325
1326 // Adds and starts tracker scrapers for tracker URLs that aren't already
1327 // running.
1328 func (t *Torrent) startMissingTrackerScrapers() {
1329         if t.cl.config.DisableTrackers {
1330                 return
1331         }
1332         t.startScrapingTracker(t.metainfo.Announce)
1333         for _, tier := range t.metainfo.AnnounceList {
1334                 for _, url := range tier {
1335                         t.startScrapingTracker(url)
1336                 }
1337         }
1338 }
1339
1340 // Returns an AnnounceRequest with fields filled out to defaults and current
1341 // values.
1342 func (t *Torrent) announceRequest() tracker.AnnounceRequest {
1343         // Note that IPAddress is not set. It's set for UDP inside the tracker
1344         // code, since it's dependent on the network in use.
1345         return tracker.AnnounceRequest{
1346                 Event:    tracker.None,
1347                 NumWant:  -1,
1348                 Port:     uint16(t.cl.incomingPeerPort()),
1349                 PeerId:   t.cl.peerID,
1350                 InfoHash: t.infoHash,
1351                 Key:      t.cl.announceKey(),
1352
1353                 // The following are vaguely described in BEP 3.
1354
1355                 Left:     t.bytesLeftAnnounce(),
1356                 Uploaded: t.stats.BytesWrittenData.Int64(),
1357                 // There's no mention of wasted or unwanted download in the BEP.
1358                 Downloaded: t.stats.BytesReadUsefulData.Int64(),
1359         }
1360 }
1361
1362 // Adds peers revealed in an announce until the announce ends, or we have
1363 // enough peers.
1364 func (t *Torrent) consumeDHTAnnounce(pvs <-chan dht.PeersValues) {
1365         cl := t.cl
1366         // Count all the unique addresses we got during this announce.
1367         allAddrs := make(map[string]struct{})
1368         for {
1369                 select {
1370                 case v, ok := <-pvs:
1371                         if !ok {
1372                                 return
1373                         }
1374                         addPeers := make([]Peer, 0, len(v.Peers))
1375                         for _, cp := range v.Peers {
1376                                 if cp.Port == 0 {
1377                                         // Can't do anything with this.
1378                                         continue
1379                                 }
1380                                 addPeers = append(addPeers, Peer{
1381                                         IP:     cp.IP[:],
1382                                         Port:   cp.Port,
1383                                         Source: peerSourceDHTGetPeers,
1384                                 })
1385                                 key := (&net.UDPAddr{
1386                                         IP:   cp.IP[:],
1387                                         Port: cp.Port,
1388                                 }).String()
1389                                 allAddrs[key] = struct{}{}
1390                         }
1391                         cl.mu.Lock()
1392                         t.addPeers(addPeers)
1393                         numPeers := t.peers.Len()
1394                         cl.mu.Unlock()
1395                         if numPeers >= cl.config.TorrentPeersHighWater {
1396                                 return
1397                         }
1398                 case <-t.closed.LockedChan(&cl.mu):
1399                         return
1400                 }
1401         }
1402 }
1403
1404 func (t *Torrent) announceDHT(impliedPort bool, s *dht.Server) (err error) {
1405         cl := t.cl
1406         ps, err := s.Announce(t.infoHash, cl.incomingPeerPort(), impliedPort)
1407         if err != nil {
1408                 return
1409         }
1410         t.consumeDHTAnnounce(ps.Peers)
1411         ps.Close()
1412         return
1413 }
1414
1415 func (t *Torrent) dhtAnnouncer(s *dht.Server) {
1416         cl := t.cl
1417         for {
1418                 select {
1419                 case <-t.wantPeersEvent.LockedChan(&cl.mu):
1420                 case <-t.closed.LockedChan(&cl.mu):
1421                         return
1422                 }
1423                 err := t.announceDHT(true, s)
1424                 func() {
1425                         cl.mu.Lock()
1426                         defer cl.mu.Unlock()
1427                         if err == nil {
1428                                 t.numDHTAnnounces++
1429                         } else {
1430                                 log.Printf("error announcing %q to DHT: %s", t, err)
1431                         }
1432                 }()
1433                 select {
1434                 case <-t.closed.LockedChan(&cl.mu):
1435                         return
1436                 case <-time.After(5 * time.Minute):
1437                 }
1438         }
1439 }
1440
1441 func (t *Torrent) addPeers(peers []Peer) {
1442         for _, p := range peers {
1443                 t.addPeer(p)
1444         }
1445 }
1446
1447 func (t *Torrent) Stats() TorrentStats {
1448         t.cl.mu.RLock()
1449         defer t.cl.mu.RUnlock()
1450         return t.statsLocked()
1451 }
1452
1453 func (t *Torrent) statsLocked() (ret TorrentStats) {
1454         ret.ActivePeers = len(t.conns)
1455         ret.HalfOpenPeers = len(t.halfOpen)
1456         ret.PendingPeers = t.peers.Len()
1457         ret.TotalPeers = t.numTotalPeers()
1458         ret.ConnectedSeeders = 0
1459         for c := range t.conns {
1460                 if all, ok := c.peerHasAllPieces(); all && ok {
1461                         ret.ConnectedSeeders++
1462                 }
1463         }
1464         ret.ConnStats = t.stats.Copy()
1465         return
1466 }
1467
1468 // The total number of peers in the torrent.
1469 func (t *Torrent) numTotalPeers() int {
1470         peers := make(map[string]struct{})
1471         for conn := range t.conns {
1472                 ra := conn.conn.RemoteAddr()
1473                 if ra == nil {
1474                         // It's been closed and doesn't support RemoteAddr.
1475                         continue
1476                 }
1477                 peers[ra.String()] = struct{}{}
1478         }
1479         for addr := range t.halfOpen {
1480                 peers[addr] = struct{}{}
1481         }
1482         t.peers.Each(func(peer Peer) {
1483                 peers[fmt.Sprintf("%s:%d", peer.IP, peer.Port)] = struct{}{}
1484         })
1485         return len(peers)
1486 }
1487
1488 // Reconcile bytes transferred before connection was associated with a
1489 // torrent.
1490 func (t *Torrent) reconcileHandshakeStats(c *connection) {
1491         if c.stats != (ConnStats{
1492                 // Handshakes should only increment these fields:
1493                 BytesWritten: c.stats.BytesWritten,
1494                 BytesRead:    c.stats.BytesRead,
1495         }) {
1496                 panic("bad stats")
1497         }
1498         c.postHandshakeStats(func(cs *ConnStats) {
1499                 cs.BytesRead.Add(c.stats.BytesRead.Int64())
1500                 cs.BytesWritten.Add(c.stats.BytesWritten.Int64())
1501         })
1502         c.reconciledHandshakeStats = true
1503 }
1504
1505 // Returns true if the connection is added.
1506 func (t *Torrent) addConnection(c *connection) (err error) {
1507         defer func() {
1508                 if err == nil {
1509                         torrent.Add("added connections", 1)
1510                 }
1511         }()
1512         if t.closed.IsSet() {
1513                 return errors.New("torrent closed")
1514         }
1515         for c0 := range t.conns {
1516                 if c.PeerID != c0.PeerID {
1517                         continue
1518                 }
1519                 if !t.cl.config.dropDuplicatePeerIds {
1520                         continue
1521                 }
1522                 if left, ok := c.hasPreferredNetworkOver(c0); ok && left {
1523                         c0.Close()
1524                         t.deleteConnection(c0)
1525                 } else {
1526                         return errors.New("existing connection preferred")
1527                 }
1528         }
1529         if len(t.conns) >= t.maxEstablishedConns {
1530                 c := t.worstBadConn()
1531                 if c == nil {
1532                         return errors.New("don't want conns")
1533                 }
1534                 if t.cl.config.Debug && missinggo.CryHeard() {
1535                         log.Printf("%s: dropping connection to make room for new one:\n    %v", t, c)
1536                 }
1537                 c.Close()
1538                 t.deleteConnection(c)
1539         }
1540         if len(t.conns) >= t.maxEstablishedConns {
1541                 panic(len(t.conns))
1542         }
1543         t.conns[c] = struct{}{}
1544         return nil
1545 }
1546
1547 func (t *Torrent) wantConns() bool {
1548         if !t.networkingEnabled {
1549                 return false
1550         }
1551         if t.closed.IsSet() {
1552                 return false
1553         }
1554         if !t.seeding() && !t.needData() {
1555                 return false
1556         }
1557         if len(t.conns) < t.maxEstablishedConns {
1558                 return true
1559         }
1560         return t.worstBadConn() != nil
1561 }
1562
1563 func (t *Torrent) SetMaxEstablishedConns(max int) (oldMax int) {
1564         t.cl.mu.Lock()
1565         defer t.cl.mu.Unlock()
1566         oldMax = t.maxEstablishedConns
1567         t.maxEstablishedConns = max
1568         wcs := slices.HeapInterface(slices.FromMapKeys(t.conns), worseConn)
1569         for len(t.conns) > t.maxEstablishedConns && wcs.Len() > 0 {
1570                 t.dropConnection(wcs.Pop().(*connection))
1571         }
1572         t.openNewConns()
1573         return oldMax
1574 }
1575
1576 func (t *Torrent) mu() missinggo.RWLocker {
1577         return &t.cl.mu
1578 }
1579
1580 func (t *Torrent) pieceHashed(piece pieceIndex, correct bool) {
1581         log.Fmsg("hashed piece %d", piece).Add("piece", piece).Add("passed", correct).AddValue(debugLogValue).Log(t.logger)
1582         if t.closed.IsSet() {
1583                 return
1584         }
1585         p := &t.pieces[piece]
1586         touchers := t.reapPieceTouchers(piece)
1587         if p.storageCompletionOk {
1588                 // Don't score the first time a piece is hashed, it could be an
1589                 // initial check.
1590                 if correct {
1591                         pieceHashedCorrect.Add(1)
1592                 } else {
1593                         log.Printf("%s: piece %d (%s) failed hash: %d connections contributed", t, piece, p.hash, len(touchers))
1594                         pieceHashedNotCorrect.Add(1)
1595                 }
1596         }
1597         if correct {
1598                 if len(touchers) != 0 {
1599                         // Don't increment stats above connection-level for every involved
1600                         // connection.
1601                         t.allStats((*ConnStats).incrementPiecesDirtiedGood)
1602                 }
1603                 for _, c := range touchers {
1604                         c.stats.incrementPiecesDirtiedGood()
1605                 }
1606                 err := p.Storage().MarkComplete()
1607                 if err != nil {
1608                         log.Printf("%T: error marking piece complete %d: %s", t.storage, piece, err)
1609                 }
1610         } else {
1611                 if len(touchers) != 0 {
1612                         // Don't increment stats above connection-level for every involved
1613                         // connection.
1614                         t.allStats((*ConnStats).incrementPiecesDirtiedBad)
1615                         for _, c := range touchers {
1616                                 // Y u do dis peer?!
1617                                 c.stats.incrementPiecesDirtiedBad()
1618                         }
1619                         slices.Sort(touchers, connLessTrusted)
1620                         if t.cl.config.Debug {
1621                                 log.Printf("dropping first corresponding conn from trust: %v", func() (ret []int64) {
1622                                         for _, c := range touchers {
1623                                                 ret = append(ret, c.netGoodPiecesDirtied())
1624                                         }
1625                                         return
1626                                 }())
1627                         }
1628                         c := touchers[0]
1629                         t.cl.banPeerIP(missinggo.AddrIP(c.remoteAddr()))
1630                         c.Drop()
1631                 }
1632                 t.onIncompletePiece(piece)
1633                 p.Storage().MarkNotComplete()
1634         }
1635         t.updatePieceCompletion(piece)
1636 }
1637
1638 func (t *Torrent) cancelRequestsForPiece(piece pieceIndex) {
1639         // TODO: Make faster
1640         for cn := range t.conns {
1641                 cn.tickleWriter()
1642         }
1643 }
1644
1645 func (t *Torrent) onPieceCompleted(piece pieceIndex) {
1646         t.pendAllChunkSpecs(piece)
1647         t.cancelRequestsForPiece(piece)
1648         for conn := range t.conns {
1649                 conn.Have(piece)
1650         }
1651 }
1652
1653 // Called when a piece is found to be not complete.
1654 func (t *Torrent) onIncompletePiece(piece pieceIndex) {
1655         if t.pieceAllDirty(piece) {
1656                 t.pendAllChunkSpecs(piece)
1657         }
1658         if !t.wantPieceIndex(piece) {
1659                 // log.Printf("piece %d incomplete and unwanted", piece)
1660                 return
1661         }
1662         // We could drop any connections that we told we have a piece that we
1663         // don't here. But there's a test failure, and it seems clients don't care
1664         // if you request pieces that you already claim to have. Pruning bad
1665         // connections might just remove any connections that aren't treating us
1666         // favourably anyway.
1667
1668         // for c := range t.conns {
1669         //      if c.sentHave(piece) {
1670         //              c.Drop()
1671         //      }
1672         // }
1673         for conn := range t.conns {
1674                 if conn.PeerHasPiece(piece) {
1675                         conn.updateRequests()
1676                 }
1677         }
1678 }
1679
1680 func (t *Torrent) verifyPiece(piece pieceIndex) {
1681         cl := t.cl
1682         cl.mu.Lock()
1683         defer cl.mu.Unlock()
1684         p := &t.pieces[piece]
1685         defer func() {
1686                 p.numVerifies++
1687                 cl.event.Broadcast()
1688         }()
1689         for p.hashing || t.storage == nil {
1690                 cl.event.Wait()
1691         }
1692         if !p.t.piecesQueuedForHash.Remove(bitmap.BitIndex(piece)) {
1693                 panic("piece was not queued")
1694         }
1695         t.updatePiecePriority(piece)
1696         if t.closed.IsSet() || t.pieceComplete(piece) {
1697                 return
1698         }
1699         p.hashing = true
1700         t.publishPieceChange(piece)
1701         t.updatePiecePriority(piece)
1702         t.storageLock.RLock()
1703         cl.mu.Unlock()
1704         sum := t.hashPiece(piece)
1705         t.storageLock.RUnlock()
1706         cl.mu.Lock()
1707         p.hashing = false
1708         t.updatePiecePriority(piece)
1709         t.pieceHashed(piece, sum == p.hash)
1710         t.publishPieceChange(piece)
1711 }
1712
1713 // Return the connections that touched a piece, and clear the entries while
1714 // doing it.
1715 func (t *Torrent) reapPieceTouchers(piece pieceIndex) (ret []*connection) {
1716         for c := range t.pieces[piece].dirtiers {
1717                 delete(c.peerTouchedPieces, piece)
1718                 ret = append(ret, c)
1719         }
1720         t.pieces[piece].dirtiers = nil
1721         return
1722 }
1723
1724 func (t *Torrent) connsAsSlice() (ret []*connection) {
1725         for c := range t.conns {
1726                 ret = append(ret, c)
1727         }
1728         return
1729 }
1730
1731 // Currently doesn't really queue, but should in the future.
1732 func (t *Torrent) queuePieceCheck(pieceIndex pieceIndex) {
1733         piece := &t.pieces[pieceIndex]
1734         if piece.queuedForHash() {
1735                 return
1736         }
1737         t.piecesQueuedForHash.Add(bitmap.BitIndex(pieceIndex))
1738         t.publishPieceChange(pieceIndex)
1739         t.updatePiecePriority(pieceIndex)
1740         go t.verifyPiece(pieceIndex)
1741 }
1742
1743 func (t *Torrent) VerifyData() {
1744         for i := pieceIndex(0); i < t.NumPieces(); i++ {
1745                 t.Piece(i).VerifyData()
1746         }
1747 }
1748
1749 // Start the process of connecting to the given peer for the given torrent if
1750 // appropriate.
1751 func (t *Torrent) initiateConn(peer Peer) {
1752         if peer.Id == t.cl.peerID {
1753                 return
1754         }
1755         if t.cl.badPeerIPPort(peer.IP, peer.Port) {
1756                 return
1757         }
1758         addr := net.JoinHostPort(peer.IP.String(), fmt.Sprintf("%d", peer.Port))
1759         if t.addrActive(addr) {
1760                 return
1761         }
1762         t.halfOpen[addr] = peer
1763         go t.cl.outgoingConnection(t, addr, peer.Source)
1764 }
1765
1766 func (t *Torrent) AddClientPeer(cl *Client) {
1767         t.AddPeers(func() (ps []Peer) {
1768                 for _, la := range cl.ListenAddrs() {
1769                         ps = append(ps, Peer{
1770                                 IP:   missinggo.AddrIP(la),
1771                                 Port: missinggo.AddrPort(la),
1772                         })
1773                 }
1774                 return
1775         }())
1776 }
1777
1778 // All stats that include this Torrent. Useful when we want to increment
1779 // ConnStats but not for every connection.
1780 func (t *Torrent) allStats(f func(*ConnStats)) {
1781         f(&t.stats)
1782         f(&t.cl.stats)
1783 }
1784
1785 func (t *Torrent) hashingPiece(i pieceIndex) bool {
1786         return t.pieces[i].hashing
1787 }
1788
1789 func (t *Torrent) pieceQueuedForHash(i pieceIndex) bool {
1790         return t.piecesQueuedForHash.Get(bitmap.BitIndex(i))
1791 }
1792
1793 func (t *Torrent) dialTimeout() time.Duration {
1794         return reducedDialTimeout(t.cl.config.MinDialTimeout, t.cl.config.NominalDialTimeout, t.cl.config.HalfOpenConnsPerTorrent, t.peers.Len())
1795 }