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