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