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