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