]> Sergey Matveev's repositories - btrtrc.git/blob - peerconn.go
Fix up some crashes around piece availability
[btrtrc.git] / peerconn.go
1 package torrent
2
3 import (
4         "bufio"
5         "bytes"
6         "errors"
7         "fmt"
8         "io"
9         "math/rand"
10         "net"
11         "sort"
12         "strconv"
13         "strings"
14         "sync"
15         "time"
16
17         "github.com/anacrolix/log"
18         "github.com/anacrolix/missinggo"
19         "github.com/anacrolix/missinggo/iter"
20         "github.com/anacrolix/missinggo/v2/bitmap"
21         "github.com/anacrolix/missinggo/v2/prioritybitmap"
22         "github.com/anacrolix/multiless"
23         "github.com/anacrolix/torrent/metainfo"
24
25         "github.com/anacrolix/torrent/bencode"
26         "github.com/anacrolix/torrent/mse"
27         pp "github.com/anacrolix/torrent/peer_protocol"
28 )
29
30 type PeerSource string
31
32 const (
33         PeerSourceTracker         = "Tr"
34         PeerSourceIncoming        = "I"
35         PeerSourceDhtGetPeers     = "Hg" // Peers we found by searching a DHT.
36         PeerSourceDhtAnnouncePeer = "Ha" // Peers that were announced to us by a DHT.
37         PeerSourcePex             = "X"
38         // The peer was given directly, such as through a magnet link.
39         PeerSourceDirect = "M"
40 )
41
42 type peerRequestState struct {
43         data []byte
44 }
45
46 type PeerRemoteAddr interface {
47         String() string
48 }
49
50 // Since we have to store all the requests in memory, we can't reasonably exceed what would be
51 // indexable with the memory space available.
52 type maxRequests = int
53
54 type Peer struct {
55         // First to ensure 64-bit alignment for atomics. See #262.
56         _stats ConnStats
57
58         t *Torrent
59
60         peerImpl
61         callbacks *Callbacks
62
63         outgoing   bool
64         Network    string
65         RemoteAddr PeerRemoteAddr
66         // True if the connection is operating over MSE obfuscation.
67         headerEncrypted bool
68         cryptoMethod    mse.CryptoMethod
69         Discovery       PeerSource
70         trusted         bool
71         closed          missinggo.Event
72         // Set true after we've added our ConnStats generated during handshake to
73         // other ConnStat instances as determined when the *Torrent became known.
74         reconciledHandshakeStats bool
75
76         lastMessageReceived     time.Time
77         completedHandshake      time.Time
78         lastUsefulChunkReceived time.Time
79         lastChunkSent           time.Time
80
81         // Stuff controlled by the local peer.
82         interested           bool
83         lastBecameInterested time.Time
84         priorInterest        time.Duration
85
86         lastStartedExpectingToReceiveChunks time.Time
87         cumulativeExpectedToReceiveChunks   time.Duration
88         _chunksReceivedWhileExpecting       int64
89
90         choking                                bool
91         requests                               map[Request]struct{}
92         piecesReceivedSinceLastRequestUpdate   maxRequests
93         maxPiecesReceivedBetweenRequestUpdates maxRequests
94         // Chunks that we might reasonably expect to receive from the peer. Due to
95         // latency, buffering, and implementation differences, we may receive
96         // chunks that are no longer in the set of requests actually want.
97         validReceiveChunks map[Request]int
98         // Indexed by metadata piece, set to true if posted and pending a
99         // response.
100         metadataRequests []bool
101         sentHaves        bitmap.Bitmap
102
103         // Stuff controlled by the remote peer.
104         peerInterested        bool
105         peerChoking           bool
106         peerRequests          map[Request]*peerRequestState
107         PeerPrefersEncryption bool // as indicated by 'e' field in extension handshake
108         PeerListenPort        int
109         // The pieces the peer has claimed to have.
110         _peerPieces bitmap.Bitmap
111         // The peer has everything. This can occur due to a special message, when
112         // we may not even know the number of pieces in the torrent yet.
113         peerSentHaveAll bool
114         // The highest possible number of pieces the torrent could have based on
115         // communication with the peer. Generally only useful until we have the
116         // torrent info.
117         peerMinPieces pieceIndex
118         // Pieces we've accepted chunks for from the peer.
119         peerTouchedPieces map[pieceIndex]struct{}
120         peerAllowedFast   bitmap.Bitmap
121
122         PeerMaxRequests  maxRequests // Maximum pending requests the peer allows.
123         PeerExtensionIDs map[pp.ExtensionName]pp.ExtensionNumber
124         PeerClientName   string
125
126         pieceInclination   []int
127         _pieceRequestOrder prioritybitmap.PriorityBitmap
128
129         logger log.Logger
130 }
131
132 // Maintains the state of a BitTorrent-protocol based connection with a peer.
133 type PeerConn struct {
134         Peer
135
136         // A string that should identify the PeerConn's net.Conn endpoints. The net.Conn could
137         // be wrapping WebRTC, uTP, or TCP etc. Used in writing the conn status for peers.
138         connString string
139
140         // See BEP 3 etc.
141         PeerID             PeerID
142         PeerExtensionBytes pp.PeerExtensionBits
143
144         // The actual Conn, used for closing, and setting socket options.
145         conn net.Conn
146         // The Reader and Writer for this Conn, with hooks installed for stats,
147         // limiting, deadlines etc.
148         w io.Writer
149         r io.Reader
150
151         writeBuffer *bytes.Buffer
152         uploadTimer *time.Timer
153         writerCond  sync.Cond
154
155         pex pexConnState
156 }
157
158 func (cn *PeerConn) connStatusString() string {
159         return fmt.Sprintf("%+-55q %s %s", cn.PeerID, cn.PeerExtensionBytes, cn.connString)
160 }
161
162 func (cn *Peer) updateExpectingChunks() {
163         if cn.expectingChunks() {
164                 if cn.lastStartedExpectingToReceiveChunks.IsZero() {
165                         cn.lastStartedExpectingToReceiveChunks = time.Now()
166                 }
167         } else {
168                 if !cn.lastStartedExpectingToReceiveChunks.IsZero() {
169                         cn.cumulativeExpectedToReceiveChunks += time.Since(cn.lastStartedExpectingToReceiveChunks)
170                         cn.lastStartedExpectingToReceiveChunks = time.Time{}
171                 }
172         }
173 }
174
175 func (cn *Peer) expectingChunks() bool {
176         if len(cn.requests) == 0 {
177                 return false
178         }
179         if !cn.interested {
180                 return false
181         }
182         for r := range cn.requests {
183                 if !cn.remoteChokingPiece(r.Index.Int()) {
184                         return true
185                 }
186         }
187         return false
188 }
189
190 func (cn *Peer) remoteChokingPiece(piece pieceIndex) bool {
191         return cn.peerChoking && !cn.peerAllowedFast.Contains(bitmap.BitIndex(piece))
192 }
193
194 // Returns true if the connection is over IPv6.
195 func (cn *PeerConn) ipv6() bool {
196         ip := cn.remoteIp()
197         if ip.To4() != nil {
198                 return false
199         }
200         return len(ip) == net.IPv6len
201 }
202
203 // Returns true the if the dialer/initiator has the lower client peer ID. TODO: Find the
204 // specification for this.
205 func (cn *PeerConn) isPreferredDirection() bool {
206         return bytes.Compare(cn.t.cl.peerID[:], cn.PeerID[:]) < 0 == cn.outgoing
207 }
208
209 // Returns whether the left connection should be preferred over the right one,
210 // considering only their networking properties. If ok is false, we can't
211 // decide.
212 func (l *PeerConn) hasPreferredNetworkOver(r *PeerConn) (left, ok bool) {
213         var ml multiLess
214         ml.NextBool(l.isPreferredDirection(), r.isPreferredDirection())
215         ml.NextBool(!l.utp(), !r.utp())
216         ml.NextBool(l.ipv6(), r.ipv6())
217         return ml.FinalOk()
218 }
219
220 func (cn *Peer) cumInterest() time.Duration {
221         ret := cn.priorInterest
222         if cn.interested {
223                 ret += time.Since(cn.lastBecameInterested)
224         }
225         return ret
226 }
227
228 func (cn *Peer) peerHasAllPieces() (all bool, known bool) {
229         if cn.peerSentHaveAll {
230                 return true, true
231         }
232         if !cn.t.haveInfo() {
233                 return false, false
234         }
235         return bitmap.Flip(cn._peerPieces, 0, bitmap.BitRange(cn.t.numPieces())).IsEmpty(), true
236 }
237
238 func (cn *PeerConn) locker() *lockWithDeferreds {
239         return cn.t.cl.locker()
240 }
241
242 func (cn *Peer) supportsExtension(ext pp.ExtensionName) bool {
243         _, ok := cn.PeerExtensionIDs[ext]
244         return ok
245 }
246
247 // The best guess at number of pieces in the torrent for this peer.
248 func (cn *Peer) bestPeerNumPieces() pieceIndex {
249         if cn.t.haveInfo() {
250                 return cn.t.numPieces()
251         }
252         return cn.peerMinPieces
253 }
254
255 func (cn *Peer) completedString() string {
256         have := pieceIndex(cn._peerPieces.Len())
257         if cn.peerSentHaveAll {
258                 have = cn.bestPeerNumPieces()
259         }
260         return fmt.Sprintf("%d/%d", have, cn.bestPeerNumPieces())
261 }
262
263 func (cn *PeerConn) onGotInfo(info *metainfo.Info) {
264         cn.setNumPieces(info.NumPieces())
265 }
266
267 // Correct the PeerPieces slice length. Return false if the existing slice is invalid, such as by
268 // receiving badly sized BITFIELD, or invalid HAVE messages.
269 func (cn *PeerConn) setNumPieces(num pieceIndex) {
270         cn._peerPieces.RemoveRange(bitmap.BitRange(num), bitmap.ToEnd)
271         cn.peerPiecesChanged()
272 }
273
274 func eventAgeString(t time.Time) string {
275         if t.IsZero() {
276                 return "never"
277         }
278         return fmt.Sprintf("%.2fs ago", time.Since(t).Seconds())
279 }
280
281 func (cn *PeerConn) connectionFlags() (ret string) {
282         c := func(b byte) {
283                 ret += string([]byte{b})
284         }
285         if cn.cryptoMethod == mse.CryptoMethodRC4 {
286                 c('E')
287         } else if cn.headerEncrypted {
288                 c('e')
289         }
290         ret += string(cn.Discovery)
291         if cn.utp() {
292                 c('U')
293         }
294         return
295 }
296
297 func (cn *PeerConn) utp() bool {
298         return parseNetworkString(cn.Network).Udp
299 }
300
301 // Inspired by https://github.com/transmission/transmission/wiki/Peer-Status-Text.
302 func (cn *Peer) statusFlags() (ret string) {
303         c := func(b byte) {
304                 ret += string([]byte{b})
305         }
306         if cn.interested {
307                 c('i')
308         }
309         if cn.choking {
310                 c('c')
311         }
312         c('-')
313         ret += cn.connectionFlags()
314         c('-')
315         if cn.peerInterested {
316                 c('i')
317         }
318         if cn.peerChoking {
319                 c('c')
320         }
321         return
322 }
323
324 func (cn *Peer) downloadRate() float64 {
325         num := cn._stats.BytesReadUsefulData.Int64()
326         if num == 0 {
327                 return 0
328         }
329         return float64(num) / cn.totalExpectingTime().Seconds()
330 }
331
332 func (cn *Peer) numRequestsByPiece() (ret map[pieceIndex]int) {
333         ret = make(map[pieceIndex]int)
334         for r := range cn.requests {
335                 ret[pieceIndex(r.Index)]++
336         }
337         return
338 }
339
340 func (cn *Peer) writeStatus(w io.Writer, t *Torrent) {
341         // \t isn't preserved in <pre> blocks?
342         if cn.closed.IsSet() {
343                 fmt.Fprint(w, "CLOSED: ")
344         }
345         fmt.Fprintln(w, cn.connStatusString())
346         prio, err := cn.peerPriority()
347         prioStr := fmt.Sprintf("%08x", prio)
348         if err != nil {
349                 prioStr += ": " + err.Error()
350         }
351         fmt.Fprintf(w, "    bep40-prio: %v\n", prioStr)
352         fmt.Fprintf(w, "    last msg: %s, connected: %s, last helpful: %s, itime: %s, etime: %s\n",
353                 eventAgeString(cn.lastMessageReceived),
354                 eventAgeString(cn.completedHandshake),
355                 eventAgeString(cn.lastHelpful()),
356                 cn.cumInterest(),
357                 cn.totalExpectingTime(),
358         )
359         fmt.Fprintf(w,
360                 "    %s completed, %d pieces touched, good chunks: %v/%v-%v reqq: %d/(%d/%d)-%d/%d, flags: %s, dr: %.1f KiB/s\n",
361                 cn.completedString(),
362                 len(cn.peerTouchedPieces),
363                 &cn._stats.ChunksReadUseful,
364                 &cn._stats.ChunksRead,
365                 &cn._stats.ChunksWritten,
366                 cn.numLocalRequests(),
367                 cn.nominalMaxRequests(),
368                 cn.PeerMaxRequests,
369                 len(cn.peerRequests),
370                 localClientReqq,
371                 cn.statusFlags(),
372                 cn.downloadRate()/(1<<10),
373         )
374         fmt.Fprintf(w, "    requested pieces:")
375         type pieceNumRequestsType struct {
376                 piece       pieceIndex
377                 numRequests int
378         }
379         var pieceNumRequests []pieceNumRequestsType
380         for piece, count := range cn.numRequestsByPiece() {
381                 pieceNumRequests = append(pieceNumRequests, pieceNumRequestsType{piece, count})
382         }
383         sort.Slice(pieceNumRequests, func(i, j int) bool {
384                 return pieceNumRequests[i].piece < pieceNumRequests[j].piece
385         })
386         for _, elem := range pieceNumRequests {
387                 fmt.Fprintf(w, " %v(%v)", elem.piece, elem.numRequests)
388         }
389         fmt.Fprintf(w, "\n")
390 }
391
392 func (p *Peer) close() {
393         if !p.closed.Set() {
394                 return
395         }
396         p.discardPieceInclination()
397         p._pieceRequestOrder.Clear()
398         p.peerImpl.onClose()
399         if p.t != nil {
400                 p.t.decPeerPieceAvailability(p)
401         }
402         for _, f := range p.callbacks.PeerClosed {
403                 f(p)
404         }
405 }
406
407 func (cn *PeerConn) onClose() {
408         if cn.pex.IsEnabled() {
409                 cn.pex.Close()
410         }
411         cn.tickleWriter()
412         if cn.conn != nil {
413                 cn.conn.Close()
414         }
415         if cb := cn.callbacks.PeerConnClosed; cb != nil {
416                 cb(cn)
417         }
418 }
419
420 func (cn *Peer) peerHasPiece(piece pieceIndex) bool {
421         return cn.peerSentHaveAll || cn._peerPieces.Contains(bitmap.BitIndex(piece))
422 }
423
424 // 64KiB, but temporarily less to work around an issue with WebRTC. TODO: Update when
425 // https://github.com/pion/datachannel/issues/59 is fixed.
426 const writeBufferHighWaterLen = 1 << 15
427
428 // Writes a message into the write buffer. Returns whether it's okay to keep writing. Writing is
429 // done asynchronously, so it may be that we're not able to honour backpressure from this method.
430 func (cn *PeerConn) write(msg pp.Message) bool {
431         torrent.Add(fmt.Sprintf("messages written of type %s", msg.Type.String()), 1)
432         // We don't need to track bytes here because a connection.w Writer wrapper takes care of that
433         // (although there's some delay between us recording the message, and the connection writer
434         // flushing it out.).
435         cn.writeBuffer.Write(msg.MustMarshalBinary())
436         // Last I checked only Piece messages affect stats, and we don't write those.
437         cn.wroteMsg(&msg)
438         cn.tickleWriter()
439         return !cn.writeBufferFull()
440 }
441
442 func (cn *PeerConn) writeBufferFull() bool {
443         return cn.writeBuffer.Len() >= writeBufferHighWaterLen
444 }
445
446 func (cn *PeerConn) requestMetadataPiece(index int) {
447         eID := cn.PeerExtensionIDs[pp.ExtensionNameMetadata]
448         if eID == 0 {
449                 return
450         }
451         if index < len(cn.metadataRequests) && cn.metadataRequests[index] {
452                 return
453         }
454         cn.logger.WithDefaultLevel(log.Debug).Printf("requesting metadata piece %d", index)
455         cn.write(pp.Message{
456                 Type:       pp.Extended,
457                 ExtendedID: eID,
458                 ExtendedPayload: func() []byte {
459                         b, err := bencode.Marshal(map[string]int{
460                                 "msg_type": pp.RequestMetadataExtensionMsgType,
461                                 "piece":    index,
462                         })
463                         if err != nil {
464                                 panic(err)
465                         }
466                         return b
467                 }(),
468         })
469         for index >= len(cn.metadataRequests) {
470                 cn.metadataRequests = append(cn.metadataRequests, false)
471         }
472         cn.metadataRequests[index] = true
473 }
474
475 func (cn *PeerConn) requestedMetadataPiece(index int) bool {
476         return index < len(cn.metadataRequests) && cn.metadataRequests[index]
477 }
478
479 // The actual value to use as the maximum outbound requests.
480 func (cn *Peer) nominalMaxRequests() (ret maxRequests) {
481         return int(clamp(1, 2*int64(cn.maxPiecesReceivedBetweenRequestUpdates), int64(cn.PeerMaxRequests)))
482 }
483
484 func (cn *Peer) totalExpectingTime() (ret time.Duration) {
485         ret = cn.cumulativeExpectedToReceiveChunks
486         if !cn.lastStartedExpectingToReceiveChunks.IsZero() {
487                 ret += time.Since(cn.lastStartedExpectingToReceiveChunks)
488         }
489         return
490
491 }
492
493 func (cn *PeerConn) onPeerSentCancel(r Request) {
494         if _, ok := cn.peerRequests[r]; !ok {
495                 torrent.Add("unexpected cancels received", 1)
496                 return
497         }
498         if cn.fastEnabled() {
499                 cn.reject(r)
500         } else {
501                 delete(cn.peerRequests, r)
502         }
503 }
504
505 func (cn *PeerConn) choke(msg messageWriter) (more bool) {
506         if cn.choking {
507                 return true
508         }
509         cn.choking = true
510         more = msg(pp.Message{
511                 Type: pp.Choke,
512         })
513         if cn.fastEnabled() {
514                 for r := range cn.peerRequests {
515                         // TODO: Don't reject pieces in allowed fast set.
516                         cn.reject(r)
517                 }
518         } else {
519                 cn.peerRequests = nil
520         }
521         return
522 }
523
524 func (cn *PeerConn) unchoke(msg func(pp.Message) bool) bool {
525         if !cn.choking {
526                 return true
527         }
528         cn.choking = false
529         return msg(pp.Message{
530                 Type: pp.Unchoke,
531         })
532 }
533
534 func (cn *Peer) setInterested(interested bool) bool {
535         if cn.interested == interested {
536                 return true
537         }
538         cn.interested = interested
539         if interested {
540                 cn.lastBecameInterested = time.Now()
541         } else if !cn.lastBecameInterested.IsZero() {
542                 cn.priorInterest += time.Since(cn.lastBecameInterested)
543         }
544         cn.updateExpectingChunks()
545         // log.Printf("%p: setting interest: %v", cn, interested)
546         return cn.writeInterested(interested)
547 }
548
549 func (pc *PeerConn) writeInterested(interested bool) bool {
550         return pc.write(pp.Message{
551                 Type: func() pp.MessageType {
552                         if interested {
553                                 return pp.Interested
554                         } else {
555                                 return pp.NotInterested
556                         }
557                 }(),
558         })
559 }
560
561 // The function takes a message to be sent, and returns true if more messages
562 // are okay.
563 type messageWriter func(pp.Message) bool
564
565 func (cn *Peer) shouldRequest(r Request) error {
566         if !cn.peerHasPiece(pieceIndex(r.Index)) {
567                 return errors.New("requesting piece peer doesn't have")
568         }
569         if !cn.t.peerIsActive(cn) {
570                 panic("requesting but not in active conns")
571         }
572         if cn.closed.IsSet() {
573                 panic("requesting when connection is closed")
574         }
575         if cn.t.hashingPiece(pieceIndex(r.Index)) {
576                 panic("piece is being hashed")
577         }
578         if cn.t.pieceQueuedForHash(pieceIndex(r.Index)) {
579                 panic("piece is queued for hash")
580         }
581         return nil
582 }
583
584 func (cn *Peer) request(r Request) error {
585         if err := cn.shouldRequest(r); err != nil {
586                 panic(err)
587         }
588         if _, ok := cn.requests[r]; ok {
589                 return nil
590         }
591         if cn.numLocalRequests() >= cn.nominalMaxRequests() {
592                 return errors.New("too many outstanding requests")
593         }
594         if cn.requests == nil {
595                 cn.requests = make(map[Request]struct{})
596         }
597         cn.requests[r] = struct{}{}
598         if cn.validReceiveChunks == nil {
599                 cn.validReceiveChunks = make(map[Request]int)
600         }
601         cn.validReceiveChunks[r]++
602         cn.t.pendingRequests[r]++
603         cn.updateExpectingChunks()
604         for _, f := range cn.callbacks.SentRequest {
605                 f(PeerRequestEvent{cn, r})
606         }
607         cn.peerImpl._request(r)
608         return nil
609 }
610
611 func (me *PeerConn) _request(r Request) {
612         me.write(pp.Message{
613                 Type:   pp.Request,
614                 Index:  r.Index,
615                 Begin:  r.Begin,
616                 Length: r.Length,
617         })
618 }
619
620 func (me *Peer) cancel(r Request) {
621         if me.deleteRequest(r) {
622                 me.peerImpl._cancel(r)
623         }
624 }
625
626 func (me *PeerConn) _cancel(r Request) {
627         me.write(makeCancelMessage(r))
628 }
629
630 func (cn *PeerConn) fillWriteBuffer() {
631         if cn.pex.IsEnabled() {
632                 if flow := cn.pex.Share(cn.write); !flow {
633                         return
634                 }
635         }
636         cn.upload(cn.write)
637 }
638
639 // Routine that writes to the peer. Some of what to write is buffered by
640 // activity elsewhere in the Client, and some is determined locally when the
641 // connection is writable.
642 func (cn *PeerConn) writer(keepAliveTimeout time.Duration) {
643         var (
644                 lastWrite      time.Time = time.Now()
645                 keepAliveTimer *time.Timer
646         )
647         keepAliveTimer = time.AfterFunc(keepAliveTimeout, func() {
648                 cn.locker().Lock()
649                 defer cn.locker().Unlock()
650                 if time.Since(lastWrite) >= keepAliveTimeout {
651                         cn.tickleWriter()
652                 }
653                 keepAliveTimer.Reset(keepAliveTimeout)
654         })
655         cn.locker().Lock()
656         defer cn.locker().Unlock()
657         defer cn.close()
658         defer keepAliveTimer.Stop()
659         frontBuf := new(bytes.Buffer)
660         for {
661                 if cn.closed.IsSet() {
662                         return
663                 }
664                 if cn.writeBuffer.Len() == 0 {
665                         cn.fillWriteBuffer()
666                 }
667                 if cn.writeBuffer.Len() == 0 && time.Since(lastWrite) >= keepAliveTimeout && cn.useful() {
668                         cn.writeBuffer.Write(pp.Message{Keepalive: true}.MustMarshalBinary())
669                         torrent.Add("written keepalives", 1)
670                 }
671                 if cn.writeBuffer.Len() == 0 {
672                         // TODO: Minimize wakeups....
673                         cn.writerCond.Wait()
674                         continue
675                 }
676                 // Flip the buffers.
677                 frontBuf, cn.writeBuffer = cn.writeBuffer, frontBuf
678                 cn.locker().Unlock()
679                 n, err := cn.w.Write(frontBuf.Bytes())
680                 cn.locker().Lock()
681                 if n != 0 {
682                         lastWrite = time.Now()
683                         keepAliveTimer.Reset(keepAliveTimeout)
684                 }
685                 if err != nil {
686                         cn.logger.WithDefaultLevel(log.Debug).Printf("error writing: %v", err)
687                         return
688                 }
689                 if n != frontBuf.Len() {
690                         panic("short write")
691                 }
692                 frontBuf.Reset()
693         }
694 }
695
696 func (cn *PeerConn) have(piece pieceIndex) {
697         if cn.sentHaves.Get(bitmap.BitIndex(piece)) {
698                 return
699         }
700         cn.write(pp.Message{
701                 Type:  pp.Have,
702                 Index: pp.Integer(piece),
703         })
704         cn.sentHaves.Add(bitmap.BitIndex(piece))
705 }
706
707 func (cn *PeerConn) postBitfield() {
708         if cn.sentHaves.Len() != 0 {
709                 panic("bitfield must be first have-related message sent")
710         }
711         if !cn.t.haveAnyPieces() {
712                 return
713         }
714         cn.write(pp.Message{
715                 Type:     pp.Bitfield,
716                 Bitfield: cn.t.bitfield(),
717         })
718         cn.sentHaves = cn.t._completedPieces.Copy()
719 }
720
721 func (cn *PeerConn) updateRequests() {
722         // log.Print("update requests")
723         cn.tickleWriter()
724 }
725
726 // Emits the indices in the Bitmaps bms in order, never repeating any index.
727 // skip is mutated during execution, and its initial values will never be
728 // emitted.
729 func iterBitmapsDistinct(skip *bitmap.Bitmap, bms ...bitmap.Bitmap) iter.Func {
730         return func(cb iter.Callback) {
731                 for _, bm := range bms {
732                         if !iter.All(
733                                 func(_i interface{}) bool {
734                                         i := _i.(int)
735                                         if skip.Contains(bitmap.BitIndex(i)) {
736                                                 return true
737                                         }
738                                         skip.Add(bitmap.BitIndex(i))
739                                         return cb(i)
740                                 },
741                                 bm.Iter,
742                         ) {
743                                 return
744                         }
745                 }
746         }
747 }
748
749 // check callers updaterequests
750 func (cn *Peer) stopRequestingPiece(piece pieceIndex) bool {
751         return cn._pieceRequestOrder.Remove(piece)
752 }
753
754 // This is distinct from Torrent piece priority, which is the user's
755 // preference. Connection piece priority is specific to a connection and is
756 // used to pseudorandomly avoid connections always requesting the same pieces
757 // and thus wasting effort.
758 func (cn *Peer) updatePiecePriority(piece pieceIndex) bool {
759         tpp := cn.t.piecePriority(piece)
760         if !cn.peerHasPiece(piece) {
761                 tpp = PiecePriorityNone
762         }
763         if tpp == PiecePriorityNone {
764                 return cn.stopRequestingPiece(piece)
765         }
766         prio := cn.getPieceInclination()[piece]
767         return cn._pieceRequestOrder.Set(piece, prio)
768 }
769
770 func (cn *Peer) getPieceInclination() []int {
771         if cn.pieceInclination == nil {
772                 cn.pieceInclination = cn.t.getConnPieceInclination()
773         }
774         return cn.pieceInclination
775 }
776
777 func (cn *Peer) discardPieceInclination() {
778         if cn.pieceInclination == nil {
779                 return
780         }
781         cn.t.putPieceInclination(cn.pieceInclination)
782         cn.pieceInclination = nil
783 }
784
785 func (cn *Peer) peerPiecesChanged() {
786         if cn.t.haveInfo() {
787                 prioritiesChanged := false
788                 for i := pieceIndex(0); i < cn.t.numPieces(); i++ {
789                         if cn.updatePiecePriority(i) {
790                                 prioritiesChanged = true
791                         }
792                 }
793                 if prioritiesChanged {
794                         cn.updateRequests()
795                 }
796         }
797         cn.t.maybeDropMutuallyCompletePeer(cn)
798 }
799
800 func (cn *PeerConn) raisePeerMinPieces(newMin pieceIndex) {
801         if newMin > cn.peerMinPieces {
802                 cn.peerMinPieces = newMin
803         }
804 }
805
806 func (cn *PeerConn) peerSentHave(piece pieceIndex) error {
807         if cn.t.haveInfo() && piece >= cn.t.numPieces() || piece < 0 {
808                 return errors.New("invalid piece")
809         }
810         if cn.peerHasPiece(piece) {
811                 return nil
812         }
813         cn.raisePeerMinPieces(piece + 1)
814         if !cn.peerHasPiece(piece) {
815                 cn.t.incPieceAvailability(piece)
816         }
817         cn._peerPieces.Set(bitmap.BitIndex(piece), true)
818         cn.t.maybeDropMutuallyCompletePeer(&cn.Peer)
819         if cn.updatePiecePriority(piece) {
820                 cn.updateRequests()
821         }
822         return nil
823 }
824
825 func (cn *PeerConn) peerSentBitfield(bf []bool) error {
826         if len(bf)%8 != 0 {
827                 panic("expected bitfield length divisible by 8")
828         }
829         // We know that the last byte means that at most the last 7 bits are wasted.
830         cn.raisePeerMinPieces(pieceIndex(len(bf) - 7))
831         if cn.t.haveInfo() && len(bf) > int(cn.t.numPieces()) {
832                 // Ignore known excess pieces.
833                 bf = bf[:cn.t.numPieces()]
834         }
835         pp := cn.newPeerPieces()
836         cn.peerSentHaveAll = false
837         for i, have := range bf {
838                 if have {
839                         cn.raisePeerMinPieces(pieceIndex(i) + 1)
840                         if !pp.Contains(bitmap.BitIndex(i)) {
841                                 cn.t.incPieceAvailability(i)
842                         }
843                 } else {
844                         if pp.Contains(bitmap.BitIndex(i)) {
845                                 cn.t.decPieceAvailability(i)
846                         }
847                 }
848                 cn._peerPieces.Set(bitmap.BitIndex(i), have)
849         }
850         cn.peerPiecesChanged()
851         return nil
852 }
853
854 func (cn *Peer) onPeerHasAllPieces() {
855         t := cn.t
856         if t.haveInfo() {
857                 pp := cn.newPeerPieces()
858                 for i := range iter.N(t.numPieces()) {
859                         if !pp.Contains(bitmap.BitIndex(i)) {
860                                 t.incPieceAvailability(i)
861                         }
862                 }
863         }
864         cn.peerSentHaveAll = true
865         cn._peerPieces.Clear()
866         cn.peerPiecesChanged()
867 }
868
869 func (cn *PeerConn) onPeerSentHaveAll() error {
870         cn.onPeerHasAllPieces()
871         return nil
872 }
873
874 func (cn *PeerConn) peerSentHaveNone() error {
875         cn.t.decPeerPieceAvailability(&cn.Peer)
876         cn._peerPieces.Clear()
877         cn.peerSentHaveAll = false
878         cn.peerPiecesChanged()
879         return nil
880 }
881
882 func (c *PeerConn) requestPendingMetadata() {
883         if c.t.haveInfo() {
884                 return
885         }
886         if c.PeerExtensionIDs[pp.ExtensionNameMetadata] == 0 {
887                 // Peer doesn't support this.
888                 return
889         }
890         // Request metadata pieces that we don't have in a random order.
891         var pending []int
892         for index := 0; index < c.t.metadataPieceCount(); index++ {
893                 if !c.t.haveMetadataPiece(index) && !c.requestedMetadataPiece(index) {
894                         pending = append(pending, index)
895                 }
896         }
897         rand.Shuffle(len(pending), func(i, j int) { pending[i], pending[j] = pending[j], pending[i] })
898         for _, i := range pending {
899                 c.requestMetadataPiece(i)
900         }
901 }
902
903 func (cn *PeerConn) wroteMsg(msg *pp.Message) {
904         torrent.Add(fmt.Sprintf("messages written of type %s", msg.Type.String()), 1)
905         if msg.Type == pp.Extended {
906                 for name, id := range cn.PeerExtensionIDs {
907                         if id != msg.ExtendedID {
908                                 continue
909                         }
910                         torrent.Add(fmt.Sprintf("Extended messages written for protocol %q", name), 1)
911                 }
912         }
913         cn.allStats(func(cs *ConnStats) { cs.wroteMsg(msg) })
914 }
915
916 func (cn *PeerConn) readMsg(msg *pp.Message) {
917         cn.allStats(func(cs *ConnStats) { cs.readMsg(msg) })
918 }
919
920 // After handshake, we know what Torrent and Client stats to include for a
921 // connection.
922 func (cn *Peer) postHandshakeStats(f func(*ConnStats)) {
923         t := cn.t
924         f(&t.stats)
925         f(&t.cl.stats)
926 }
927
928 // All ConnStats that include this connection. Some objects are not known
929 // until the handshake is complete, after which it's expected to reconcile the
930 // differences.
931 func (cn *Peer) allStats(f func(*ConnStats)) {
932         f(&cn._stats)
933         if cn.reconciledHandshakeStats {
934                 cn.postHandshakeStats(f)
935         }
936 }
937
938 func (cn *PeerConn) wroteBytes(n int64) {
939         cn.allStats(add(n, func(cs *ConnStats) *Count { return &cs.BytesWritten }))
940 }
941
942 func (cn *PeerConn) readBytes(n int64) {
943         cn.allStats(add(n, func(cs *ConnStats) *Count { return &cs.BytesRead }))
944 }
945
946 // Returns whether the connection could be useful to us. We're seeding and
947 // they want data, we don't have metainfo and they can provide it, etc.
948 func (c *Peer) useful() bool {
949         t := c.t
950         if c.closed.IsSet() {
951                 return false
952         }
953         if !t.haveInfo() {
954                 return c.supportsExtension("ut_metadata")
955         }
956         if t.seeding() && c.peerInterested {
957                 return true
958         }
959         if c.peerHasWantedPieces() {
960                 return true
961         }
962         return false
963 }
964
965 func (c *Peer) lastHelpful() (ret time.Time) {
966         ret = c.lastUsefulChunkReceived
967         if c.t.seeding() && c.lastChunkSent.After(ret) {
968                 ret = c.lastChunkSent
969         }
970         return
971 }
972
973 func (c *PeerConn) fastEnabled() bool {
974         return c.PeerExtensionBytes.SupportsFast() && c.t.cl.config.Extensions.SupportsFast()
975 }
976
977 func (c *PeerConn) reject(r Request) {
978         if !c.fastEnabled() {
979                 panic("fast not enabled")
980         }
981         c.write(r.ToMsg(pp.Reject))
982         delete(c.peerRequests, r)
983 }
984
985 func (c *PeerConn) onReadRequest(r Request) error {
986         requestedChunkLengths.Add(strconv.FormatUint(r.Length.Uint64(), 10), 1)
987         if _, ok := c.peerRequests[r]; ok {
988                 torrent.Add("duplicate requests received", 1)
989                 return nil
990         }
991         if c.choking {
992                 torrent.Add("requests received while choking", 1)
993                 if c.fastEnabled() {
994                         torrent.Add("requests rejected while choking", 1)
995                         c.reject(r)
996                 }
997                 return nil
998         }
999         // TODO: What if they've already requested this?
1000         if len(c.peerRequests) >= localClientReqq {
1001                 torrent.Add("requests received while queue full", 1)
1002                 if c.fastEnabled() {
1003                         c.reject(r)
1004                 }
1005                 // BEP 6 says we may close here if we choose.
1006                 return nil
1007         }
1008         if !c.t.havePiece(pieceIndex(r.Index)) {
1009                 // This isn't necessarily them screwing up. We can drop pieces
1010                 // from our storage, and can't communicate this to peers
1011                 // except by reconnecting.
1012                 requestsReceivedForMissingPieces.Add(1)
1013                 return fmt.Errorf("peer requested piece we don't have: %v", r.Index.Int())
1014         }
1015         // Check this after we know we have the piece, so that the piece length will be known.
1016         if r.Begin+r.Length > c.t.pieceLength(pieceIndex(r.Index)) {
1017                 torrent.Add("bad requests received", 1)
1018                 return errors.New("bad Request")
1019         }
1020         if c.peerRequests == nil {
1021                 c.peerRequests = make(map[Request]*peerRequestState, localClientReqq)
1022         }
1023         value := &peerRequestState{}
1024         c.peerRequests[r] = value
1025         go c.peerRequestDataReader(r, value)
1026         //c.tickleWriter()
1027         return nil
1028 }
1029
1030 func (c *PeerConn) peerRequestDataReader(r Request, prs *peerRequestState) {
1031         b, err := readPeerRequestData(r, c)
1032         c.locker().Lock()
1033         defer c.locker().Unlock()
1034         if err != nil {
1035                 c.peerRequestDataReadFailed(err, r)
1036         } else {
1037                 if b == nil {
1038                         panic("data must be non-nil to trigger send")
1039                 }
1040                 prs.data = b
1041                 c.tickleWriter()
1042         }
1043 }
1044
1045 // If this is maintained correctly, we might be able to support optional synchronous reading for
1046 // chunk sending, the way it used to work.
1047 func (c *PeerConn) peerRequestDataReadFailed(err error, r Request) {
1048         c.logger.WithDefaultLevel(log.Warning).Printf("error reading chunk for peer Request %v: %v", r, err)
1049         i := pieceIndex(r.Index)
1050         if c.t.pieceComplete(i) {
1051                 // There used to be more code here that just duplicated the following break. Piece
1052                 // completions are currently cached, so I'm not sure how helpful this update is, except to
1053                 // pull any completion changes pushed to the storage backend in failed reads that got us
1054                 // here.
1055                 c.t.updatePieceCompletion(i)
1056         }
1057         // If we failed to send a chunk, choke the peer to ensure they flush all their requests. We've
1058         // probably dropped a piece from storage, but there's no way to communicate this to the peer. If
1059         // they ask for it again, we'll kick them to allow us to send them an updated bitfield on the
1060         // next connect. TODO: Support rejecting here too.
1061         if c.choking {
1062                 c.logger.WithDefaultLevel(log.Warning).Printf("already choking peer, requests might not be rejected correctly")
1063         }
1064         c.choke(c.write)
1065 }
1066
1067 func readPeerRequestData(r Request, c *PeerConn) ([]byte, error) {
1068         b := make([]byte, r.Length)
1069         p := c.t.info.Piece(int(r.Index))
1070         n, err := c.t.readAt(b, p.Offset()+int64(r.Begin))
1071         if n == len(b) {
1072                 if err == io.EOF {
1073                         err = nil
1074                 }
1075         } else {
1076                 if err == nil {
1077                         panic("expected error")
1078                 }
1079         }
1080         return b, err
1081 }
1082
1083 func runSafeExtraneous(f func()) {
1084         if true {
1085                 go f()
1086         } else {
1087                 f()
1088         }
1089 }
1090
1091 // Processes incoming BitTorrent wire-protocol messages. The client lock is held upon entry and
1092 // exit. Returning will end the connection.
1093 func (c *PeerConn) mainReadLoop() (err error) {
1094         defer func() {
1095                 if err != nil {
1096                         torrent.Add("connection.mainReadLoop returned with error", 1)
1097                 } else {
1098                         torrent.Add("connection.mainReadLoop returned with no error", 1)
1099                 }
1100         }()
1101         t := c.t
1102         cl := t.cl
1103
1104         decoder := pp.Decoder{
1105                 R:         bufio.NewReaderSize(c.r, 1<<17),
1106                 MaxLength: 256 * 1024,
1107                 Pool:      t.chunkPool,
1108         }
1109         for {
1110                 var msg pp.Message
1111                 func() {
1112                         cl.unlock()
1113                         defer cl.lock()
1114                         err = decoder.Decode(&msg)
1115                 }()
1116                 if cb := c.callbacks.ReadMessage; cb != nil && err == nil {
1117                         cb(c, &msg)
1118                 }
1119                 if t.closed.IsSet() || c.closed.IsSet() {
1120                         return nil
1121                 }
1122                 if err != nil {
1123                         return err
1124                 }
1125                 c.readMsg(&msg)
1126                 c.lastMessageReceived = time.Now()
1127                 if msg.Keepalive {
1128                         receivedKeepalives.Add(1)
1129                         continue
1130                 }
1131                 messageTypesReceived.Add(msg.Type.String(), 1)
1132                 if msg.Type.FastExtension() && !c.fastEnabled() {
1133                         runSafeExtraneous(func() { torrent.Add("fast messages received when extension is disabled", 1) })
1134                         return fmt.Errorf("received fast extension message (type=%v) but extension is disabled", msg.Type)
1135                 }
1136                 switch msg.Type {
1137                 case pp.Choke:
1138                         c.peerChoking = true
1139                         if !c.fastEnabled() {
1140                                 c.deleteAllRequests()
1141                         }
1142                         // We can then reset our interest.
1143                         c.updateRequests()
1144                         c.updateExpectingChunks()
1145                 case pp.Unchoke:
1146                         c.peerChoking = false
1147                         c.tickleWriter()
1148                         c.updateExpectingChunks()
1149                 case pp.Interested:
1150                         c.peerInterested = true
1151                         c.tickleWriter()
1152                 case pp.NotInterested:
1153                         c.peerInterested = false
1154                         // We don't clear their requests since it isn't clear in the spec.
1155                         // We'll probably choke them for this, which will clear them if
1156                         // appropriate, and is clearly specified.
1157                 case pp.Have:
1158                         err = c.peerSentHave(pieceIndex(msg.Index))
1159                 case pp.Bitfield:
1160                         err = c.peerSentBitfield(msg.Bitfield)
1161                 case pp.Request:
1162                         r := newRequestFromMessage(&msg)
1163                         err = c.onReadRequest(r)
1164                 case pp.Piece:
1165                         err = c.receiveChunk(&msg)
1166                         if len(msg.Piece) == int(t.chunkSize) {
1167                                 t.chunkPool.Put(&msg.Piece)
1168                         }
1169                         if err != nil {
1170                                 err = fmt.Errorf("receiving chunk: %s", err)
1171                         }
1172                 case pp.Cancel:
1173                         req := newRequestFromMessage(&msg)
1174                         c.onPeerSentCancel(req)
1175                 case pp.Port:
1176                         ipa, ok := tryIpPortFromNetAddr(c.RemoteAddr)
1177                         if !ok {
1178                                 break
1179                         }
1180                         pingAddr := net.UDPAddr{
1181                                 IP:   ipa.IP,
1182                                 Port: ipa.Port,
1183                         }
1184                         if msg.Port != 0 {
1185                                 pingAddr.Port = int(msg.Port)
1186                         }
1187                         cl.eachDhtServer(func(s DhtServer) {
1188                                 go s.Ping(&pingAddr)
1189                         })
1190                 case pp.Suggest:
1191                         torrent.Add("suggests received", 1)
1192                         log.Fmsg("peer suggested piece %d", msg.Index).AddValues(c, msg.Index).SetLevel(log.Debug).Log(c.t.logger)
1193                         c.updateRequests()
1194                 case pp.HaveAll:
1195                         err = c.onPeerSentHaveAll()
1196                 case pp.HaveNone:
1197                         err = c.peerSentHaveNone()
1198                 case pp.Reject:
1199                         c.remoteRejectedRequest(newRequestFromMessage(&msg))
1200                 case pp.AllowedFast:
1201                         torrent.Add("allowed fasts received", 1)
1202                         log.Fmsg("peer allowed fast: %d", msg.Index).AddValues(c).SetLevel(log.Debug).Log(c.t.logger)
1203                         c.peerAllowedFast.Add(bitmap.BitIndex(msg.Index))
1204                         c.updateRequests()
1205                 case pp.Extended:
1206                         err = c.onReadExtendedMsg(msg.ExtendedID, msg.ExtendedPayload)
1207                 default:
1208                         err = fmt.Errorf("received unknown message type: %#v", msg.Type)
1209                 }
1210                 if err != nil {
1211                         return err
1212                 }
1213         }
1214 }
1215
1216 func (c *Peer) remoteRejectedRequest(r Request) {
1217         if c.deleteRequest(r) {
1218                 c.decExpectedChunkReceive(r)
1219         }
1220 }
1221
1222 func (c *Peer) decExpectedChunkReceive(r Request) {
1223         count := c.validReceiveChunks[r]
1224         if count == 1 {
1225                 delete(c.validReceiveChunks, r)
1226         } else if count > 1 {
1227                 c.validReceiveChunks[r] = count - 1
1228         } else {
1229                 panic(r)
1230         }
1231 }
1232
1233 func (c *PeerConn) onReadExtendedMsg(id pp.ExtensionNumber, payload []byte) (err error) {
1234         defer func() {
1235                 // TODO: Should we still do this?
1236                 if err != nil {
1237                         // These clients use their own extension IDs for outgoing message
1238                         // types, which is incorrect.
1239                         if bytes.HasPrefix(c.PeerID[:], []byte("-SD0100-")) || strings.HasPrefix(string(c.PeerID[:]), "-XL0012-") {
1240                                 err = nil
1241                         }
1242                 }
1243         }()
1244         t := c.t
1245         cl := t.cl
1246         switch id {
1247         case pp.HandshakeExtendedID:
1248                 var d pp.ExtendedHandshakeMessage
1249                 if err := bencode.Unmarshal(payload, &d); err != nil {
1250                         c.logger.Printf("error parsing extended handshake message %q: %s", payload, err)
1251                         return fmt.Errorf("unmarshalling extended handshake payload: %w", err)
1252                 }
1253                 if cb := c.callbacks.ReadExtendedHandshake; cb != nil {
1254                         cb(c, &d)
1255                 }
1256                 //c.logger.WithDefaultLevel(log.Debug).Printf("received extended handshake message:\n%s", spew.Sdump(d))
1257                 if d.Reqq != 0 {
1258                         c.PeerMaxRequests = d.Reqq
1259                 }
1260                 c.PeerClientName = d.V
1261                 if c.PeerExtensionIDs == nil {
1262                         c.PeerExtensionIDs = make(map[pp.ExtensionName]pp.ExtensionNumber, len(d.M))
1263                 }
1264                 c.PeerListenPort = d.Port
1265                 c.PeerPrefersEncryption = d.Encryption
1266                 for name, id := range d.M {
1267                         if _, ok := c.PeerExtensionIDs[name]; !ok {
1268                                 peersSupportingExtension.Add(string(name), 1)
1269                         }
1270                         c.PeerExtensionIDs[name] = id
1271                 }
1272                 if d.MetadataSize != 0 {
1273                         if err = t.setMetadataSize(d.MetadataSize); err != nil {
1274                                 return fmt.Errorf("setting metadata size to %d: %w", d.MetadataSize, err)
1275                         }
1276                 }
1277                 c.requestPendingMetadata()
1278                 if !t.cl.config.DisablePEX {
1279                         t.pex.Add(c) // we learnt enough now
1280                         c.pex.Init(c)
1281                 }
1282                 return nil
1283         case metadataExtendedId:
1284                 err := cl.gotMetadataExtensionMsg(payload, t, c)
1285                 if err != nil {
1286                         return fmt.Errorf("handling metadata extension message: %w", err)
1287                 }
1288                 return nil
1289         case pexExtendedId:
1290                 if !c.pex.IsEnabled() {
1291                         return nil // or hang-up maybe?
1292                 }
1293                 return c.pex.Recv(payload)
1294         default:
1295                 return fmt.Errorf("unexpected extended message ID: %v", id)
1296         }
1297 }
1298
1299 // Set both the Reader and Writer for the connection from a single ReadWriter.
1300 func (cn *PeerConn) setRW(rw io.ReadWriter) {
1301         cn.r = rw
1302         cn.w = rw
1303 }
1304
1305 // Returns the Reader and Writer as a combined ReadWriter.
1306 func (cn *PeerConn) rw() io.ReadWriter {
1307         return struct {
1308                 io.Reader
1309                 io.Writer
1310         }{cn.r, cn.w}
1311 }
1312
1313 // Handle a received chunk from a peer.
1314 func (c *Peer) receiveChunk(msg *pp.Message) error {
1315         t := c.t
1316         cl := t.cl
1317         chunksReceived.Add("total", 1)
1318
1319         req := newRequestFromMessage(msg)
1320
1321         if c.peerChoking {
1322                 chunksReceived.Add("while choked", 1)
1323         }
1324
1325         if c.validReceiveChunks[req] <= 0 {
1326                 chunksReceived.Add("unexpected", 1)
1327                 return errors.New("received unexpected chunk")
1328         }
1329         c.decExpectedChunkReceive(req)
1330
1331         if c.peerChoking && c.peerAllowedFast.Get(bitmap.BitIndex(req.Index)) {
1332                 chunksReceived.Add("due to allowed fast", 1)
1333         }
1334
1335         // The request needs to be deleted immediately to prevent cancels occurring asynchronously when
1336         // have actually already received the piece, while we have the Client unlocked to write the data
1337         // out.
1338         deletedRequest := false
1339         {
1340                 if _, ok := c.requests[req]; ok {
1341                         for _, f := range c.callbacks.ReceivedRequested {
1342                                 f(PeerMessageEvent{c, msg})
1343                         }
1344                 }
1345                 // Request has been satisfied.
1346                 if c.deleteRequest(req) {
1347                         deletedRequest = true
1348                         if !c.peerChoking {
1349                                 c._chunksReceivedWhileExpecting++
1350                         }
1351                 } else {
1352                         chunksReceived.Add("unwanted", 1)
1353                 }
1354         }
1355
1356         // Do we actually want this chunk?
1357         if t.haveChunk(req) {
1358                 chunksReceived.Add("wasted", 1)
1359                 c.allStats(add(1, func(cs *ConnStats) *Count { return &cs.ChunksReadWasted }))
1360                 return nil
1361         }
1362
1363         piece := &t.pieces[req.Index]
1364
1365         c.allStats(add(1, func(cs *ConnStats) *Count { return &cs.ChunksReadUseful }))
1366         c.allStats(add(int64(len(msg.Piece)), func(cs *ConnStats) *Count { return &cs.BytesReadUsefulData }))
1367         if deletedRequest {
1368                 c.piecesReceivedSinceLastRequestUpdate++
1369                 c.allStats(add(int64(len(msg.Piece)), func(cs *ConnStats) *Count { return &cs.BytesReadUsefulIntendedData }))
1370         }
1371         for _, f := range c.t.cl.config.Callbacks.ReceivedUsefulData {
1372                 f(ReceivedUsefulDataEvent{c, msg})
1373         }
1374         c.lastUsefulChunkReceived = time.Now()
1375
1376         // Need to record that it hasn't been written yet, before we attempt to do
1377         // anything with it.
1378         piece.incrementPendingWrites()
1379         // Record that we have the chunk, so we aren't trying to download it while
1380         // waiting for it to be written to storage.
1381         piece.unpendChunkIndex(chunkIndex(req.ChunkSpec, t.chunkSize))
1382
1383         // Cancel pending requests for this chunk from *other* peers.
1384         t.iterPeers(func(p *Peer) {
1385                 if p == c {
1386                         return
1387                 }
1388                 p.cancel(req)
1389         })
1390
1391         err := func() error {
1392                 cl.unlock()
1393                 defer cl.lock()
1394                 concurrentChunkWrites.Add(1)
1395                 defer concurrentChunkWrites.Add(-1)
1396                 // Write the chunk out. Note that the upper bound on chunk writing concurrency will be the
1397                 // number of connections. We write inline with receiving the chunk (with this lock dance),
1398                 // because we want to handle errors synchronously and I haven't thought of a nice way to
1399                 // defer any concurrency to the storage and have that notify the client of errors. TODO: Do
1400                 // that instead.
1401                 return t.writeChunk(int(msg.Index), int64(msg.Begin), msg.Piece)
1402         }()
1403
1404         piece.decrementPendingWrites()
1405
1406         if err != nil {
1407                 c.logger.WithDefaultLevel(log.Error).Printf("writing received chunk %v: %v", req, err)
1408                 t.pendRequest(req)
1409                 //t.updatePieceCompletion(pieceIndex(msg.Index))
1410                 t.onWriteChunkErr(err)
1411                 return nil
1412         }
1413
1414         c.onDirtiedPiece(pieceIndex(req.Index))
1415
1416         // We need to ensure the piece is only queued once, so only the last chunk writer gets this job.
1417         if t.pieceAllDirty(pieceIndex(req.Index)) && piece.pendingWrites == 0 {
1418                 t.queuePieceCheck(pieceIndex(req.Index))
1419                 // We don't pend all chunks here anymore because we don't want code dependent on the dirty
1420                 // chunk status (such as the haveChunk call above) to have to check all the various other
1421                 // piece states like queued for hash, hashing etc. This does mean that we need to be sure
1422                 // that chunk pieces are pended at an appropriate time later however.
1423         }
1424
1425         cl.event.Broadcast()
1426         // We do this because we've written a chunk, and may change PieceState.Partial.
1427         t.publishPieceChange(pieceIndex(req.Index))
1428
1429         return nil
1430 }
1431
1432 func (c *Peer) onDirtiedPiece(piece pieceIndex) {
1433         if c.peerTouchedPieces == nil {
1434                 c.peerTouchedPieces = make(map[pieceIndex]struct{})
1435         }
1436         c.peerTouchedPieces[piece] = struct{}{}
1437         ds := &c.t.pieces[piece].dirtiers
1438         if *ds == nil {
1439                 *ds = make(map[*Peer]struct{})
1440         }
1441         (*ds)[c] = struct{}{}
1442 }
1443
1444 func (c *PeerConn) uploadAllowed() bool {
1445         if c.t.cl.config.NoUpload {
1446                 return false
1447         }
1448         if c.t.dataUploadDisallowed {
1449                 return false
1450         }
1451         if c.t.seeding() {
1452                 return true
1453         }
1454         if !c.peerHasWantedPieces() {
1455                 return false
1456         }
1457         // Don't upload more than 100 KiB more than we download.
1458         if c._stats.BytesWrittenData.Int64() >= c._stats.BytesReadData.Int64()+100<<10 {
1459                 return false
1460         }
1461         return true
1462 }
1463
1464 func (c *PeerConn) setRetryUploadTimer(delay time.Duration) {
1465         if c.uploadTimer == nil {
1466                 c.uploadTimer = time.AfterFunc(delay, c.writerCond.Broadcast)
1467         } else {
1468                 c.uploadTimer.Reset(delay)
1469         }
1470 }
1471
1472 // Also handles choking and unchoking of the remote peer.
1473 func (c *PeerConn) upload(msg func(pp.Message) bool) bool {
1474         // Breaking or completing this loop means we don't want to upload to the
1475         // peer anymore, and we choke them.
1476 another:
1477         for c.uploadAllowed() {
1478                 // We want to upload to the peer.
1479                 if !c.unchoke(msg) {
1480                         return false
1481                 }
1482                 for r, state := range c.peerRequests {
1483                         if state.data == nil {
1484                                 continue
1485                         }
1486                         res := c.t.cl.config.UploadRateLimiter.ReserveN(time.Now(), int(r.Length))
1487                         if !res.OK() {
1488                                 panic(fmt.Sprintf("upload rate limiter burst size < %d", r.Length))
1489                         }
1490                         delay := res.Delay()
1491                         if delay > 0 {
1492                                 res.Cancel()
1493                                 c.setRetryUploadTimer(delay)
1494                                 // Hard to say what to return here.
1495                                 return true
1496                         }
1497                         more := c.sendChunk(r, msg, state)
1498                         delete(c.peerRequests, r)
1499                         if !more {
1500                                 return false
1501                         }
1502                         goto another
1503                 }
1504                 return true
1505         }
1506         return c.choke(msg)
1507 }
1508
1509 func (cn *PeerConn) drop() {
1510         cn.t.dropConnection(cn)
1511 }
1512
1513 func (cn *Peer) netGoodPiecesDirtied() int64 {
1514         return cn._stats.PiecesDirtiedGood.Int64() - cn._stats.PiecesDirtiedBad.Int64()
1515 }
1516
1517 func (c *Peer) peerHasWantedPieces() bool {
1518         return !c._pieceRequestOrder.IsEmpty()
1519 }
1520
1521 func (c *Peer) numLocalRequests() int {
1522         return len(c.requests)
1523 }
1524
1525 func (c *Peer) deleteRequest(r Request) bool {
1526         if _, ok := c.requests[r]; !ok {
1527                 return false
1528         }
1529         delete(c.requests, r)
1530         for _, f := range c.callbacks.DeletedRequest {
1531                 f(PeerRequestEvent{c, r})
1532         }
1533         c.updateExpectingChunks()
1534         pr := c.t.pendingRequests
1535         pr[r]--
1536         n := pr[r]
1537         if n == 0 {
1538                 delete(pr, r)
1539         }
1540         if n < 0 {
1541                 panic(n)
1542         }
1543         return true
1544 }
1545
1546 func (c *Peer) deleteAllRequests() {
1547         for r := range c.requests {
1548                 c.deleteRequest(r)
1549         }
1550         if len(c.requests) != 0 {
1551                 panic(len(c.requests))
1552         }
1553         // for c := range c.t.conns {
1554         //      c.tickleWriter()
1555         // }
1556 }
1557
1558 // This is called when something has changed that should wake the writer, such as putting stuff into
1559 // the writeBuffer, or changing some state that the writer can act on.
1560 func (c *PeerConn) tickleWriter() {
1561         c.writerCond.Broadcast()
1562 }
1563
1564 func (c *PeerConn) sendChunk(r Request, msg func(pp.Message) bool, state *peerRequestState) (more bool) {
1565         c.lastChunkSent = time.Now()
1566         return msg(pp.Message{
1567                 Type:  pp.Piece,
1568                 Index: r.Index,
1569                 Begin: r.Begin,
1570                 Piece: state.data,
1571         })
1572 }
1573
1574 func (c *PeerConn) setTorrent(t *Torrent) {
1575         if c.t != nil {
1576                 panic("connection already associated with a torrent")
1577         }
1578         c.t = t
1579         c.logger.WithDefaultLevel(log.Debug).Printf("set torrent=%v", t)
1580         t.reconcileHandshakeStats(c)
1581 }
1582
1583 func (c *Peer) peerPriority() (peerPriority, error) {
1584         return bep40Priority(c.remoteIpPort(), c.t.cl.publicAddr(c.remoteIp()))
1585 }
1586
1587 func (c *Peer) remoteIp() net.IP {
1588         host, _, _ := net.SplitHostPort(c.RemoteAddr.String())
1589         return net.ParseIP(host)
1590 }
1591
1592 func (c *Peer) remoteIpPort() IpPort {
1593         ipa, _ := tryIpPortFromNetAddr(c.RemoteAddr)
1594         return IpPort{ipa.IP, uint16(ipa.Port)}
1595 }
1596
1597 func (c *PeerConn) pexPeerFlags() pp.PexPeerFlags {
1598         f := pp.PexPeerFlags(0)
1599         if c.PeerPrefersEncryption {
1600                 f |= pp.PexPrefersEncryption
1601         }
1602         if c.outgoing {
1603                 f |= pp.PexOutgoingConn
1604         }
1605         if c.utp() {
1606                 f |= pp.PexSupportsUtp
1607         }
1608         return f
1609 }
1610
1611 // This returns the address to use if we want to dial the peer again. It incorporates the peer's
1612 // advertised listen port.
1613 func (c *PeerConn) dialAddr() PeerRemoteAddr {
1614         if !c.outgoing && c.PeerListenPort != 0 {
1615                 switch addr := c.RemoteAddr.(type) {
1616                 case *net.TCPAddr:
1617                         dialAddr := *addr
1618                         dialAddr.Port = c.PeerListenPort
1619                         return &dialAddr
1620                 case *net.UDPAddr:
1621                         dialAddr := *addr
1622                         dialAddr.Port = c.PeerListenPort
1623                         return &dialAddr
1624                 }
1625         }
1626         return c.RemoteAddr
1627 }
1628
1629 func (c *PeerConn) pexEvent(t pexEventType) pexEvent {
1630         f := c.pexPeerFlags()
1631         addr := c.dialAddr()
1632         return pexEvent{t, addr, f}
1633 }
1634
1635 func (c *PeerConn) String() string {
1636         return fmt.Sprintf("connection %p", c)
1637 }
1638
1639 func (c *Peer) trust() connectionTrust {
1640         return connectionTrust{c.trusted, c.netGoodPiecesDirtied()}
1641 }
1642
1643 type connectionTrust struct {
1644         Implicit            bool
1645         NetGoodPiecesDirted int64
1646 }
1647
1648 func (l connectionTrust) Less(r connectionTrust) bool {
1649         return multiless.New().Bool(l.Implicit, r.Implicit).Int64(l.NetGoodPiecesDirted, r.NetGoodPiecesDirted).Less()
1650 }
1651
1652 func (cn *Peer) peerMaxRequests() int {
1653         return cn.PeerMaxRequests
1654 }
1655
1656 // Returns the pieces the peer could have based on their claims. If we don't know how many pieces
1657 // are in the torrent, it could be a very large range the peer has sent HaveAll.
1658 func (cn *PeerConn) PeerPieces() bitmap.Bitmap {
1659         cn.locker().RLock()
1660         defer cn.locker().RUnlock()
1661         return cn.newPeerPieces()
1662 }
1663
1664 // Returns a new Bitmap that includes bits for all pieces the peer could have based on their claims.
1665 func (cn *Peer) newPeerPieces() bitmap.Bitmap {
1666         ret := cn._peerPieces.Copy()
1667         if cn.peerSentHaveAll {
1668                 if cn.t.haveInfo() {
1669                         ret.AddRange(0, bitmap.BitRange(cn.t.numPieces()))
1670                 } else {
1671                         ret.AddRange(0, bitmap.ToEnd)
1672                 }
1673         }
1674         return ret
1675 }
1676
1677 func (cn *Peer) pieceRequestOrder() *prioritybitmap.PriorityBitmap {
1678         return &cn._pieceRequestOrder
1679 }
1680
1681 func (cn *Peer) stats() *ConnStats {
1682         return &cn._stats
1683 }
1684
1685 func (p *Peer) TryAsPeerConn() (*PeerConn, bool) {
1686         pc, ok := p.peerImpl.(*PeerConn)
1687         return pc, ok
1688 }