]> Sergey Matveev's repositories - btrtrc.git/blob - peerconn.go
Pass tests with new full-client request strategy implementation
[btrtrc.git] / peerconn.go
1 package torrent
2
3 import (
4         "bufio"
5         "bytes"
6         "errors"
7         "fmt"
8         "io"
9         "math/rand"
10         "net"
11         "strconv"
12         "strings"
13         "sync"
14         "time"
15
16         "github.com/anacrolix/log"
17         "github.com/anacrolix/missinggo"
18         "github.com/anacrolix/missinggo/iter"
19         "github.com/anacrolix/missinggo/v2/bitmap"
20         "github.com/anacrolix/missinggo/v2/prioritybitmap"
21         "github.com/anacrolix/multiless"
22         "github.com/anacrolix/torrent/metainfo"
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         cn.tickleWriter()
406         return !cn.writeBufferFull()
407 }
408
409 func (cn *PeerConn) writeBufferFull() bool {
410         return cn.writeBuffer.Len() >= writeBufferHighWaterLen
411 }
412
413 func (cn *PeerConn) requestMetadataPiece(index int) {
414         eID := cn.PeerExtensionIDs[pp.ExtensionNameMetadata]
415         if eID == 0 {
416                 return
417         }
418         if index < len(cn.metadataRequests) && cn.metadataRequests[index] {
419                 return
420         }
421         cn.logger.WithDefaultLevel(log.Debug).Printf("requesting metadata piece %d", index)
422         cn.post(pp.Message{
423                 Type:       pp.Extended,
424                 ExtendedID: eID,
425                 ExtendedPayload: func() []byte {
426                         b, err := bencode.Marshal(map[string]int{
427                                 "msg_type": pp.RequestMetadataExtensionMsgType,
428                                 "piece":    index,
429                         })
430                         if err != nil {
431                                 panic(err)
432                         }
433                         return b
434                 }(),
435         })
436         for index >= len(cn.metadataRequests) {
437                 cn.metadataRequests = append(cn.metadataRequests, false)
438         }
439         cn.metadataRequests[index] = true
440 }
441
442 func (cn *PeerConn) requestedMetadataPiece(index int) bool {
443         return index < len(cn.metadataRequests) && cn.metadataRequests[index]
444 }
445
446 // The actual value to use as the maximum outbound requests.
447 func (cn *Peer) nominalMaxRequests() (ret int) {
448         return cn.PeerMaxRequests
449 }
450
451 func (cn *Peer) totalExpectingTime() (ret time.Duration) {
452         ret = cn.cumulativeExpectedToReceiveChunks
453         if !cn.lastStartedExpectingToReceiveChunks.IsZero() {
454                 ret += time.Since(cn.lastStartedExpectingToReceiveChunks)
455         }
456         return
457
458 }
459
460 func (cn *PeerConn) onPeerSentCancel(r Request) {
461         if _, ok := cn.peerRequests[r]; !ok {
462                 torrent.Add("unexpected cancels received", 1)
463                 return
464         }
465         if cn.fastEnabled() {
466                 cn.reject(r)
467         } else {
468                 delete(cn.peerRequests, r)
469         }
470 }
471
472 func (cn *PeerConn) choke(msg messageWriter) (more bool) {
473         if cn.choking {
474                 return true
475         }
476         cn.choking = true
477         more = msg(pp.Message{
478                 Type: pp.Choke,
479         })
480         if cn.fastEnabled() {
481                 for r := range cn.peerRequests {
482                         // TODO: Don't reject pieces in allowed fast set.
483                         cn.reject(r)
484                 }
485         } else {
486                 cn.peerRequests = nil
487         }
488         return
489 }
490
491 func (cn *PeerConn) unchoke(msg func(pp.Message) bool) bool {
492         if !cn.choking {
493                 return true
494         }
495         cn.choking = false
496         return msg(pp.Message{
497                 Type: pp.Unchoke,
498         })
499 }
500
501 func (cn *Peer) setInterested(interested bool) bool {
502         if cn.interested == interested {
503                 return true
504         }
505         cn.interested = interested
506         if interested {
507                 cn.lastBecameInterested = time.Now()
508         } else if !cn.lastBecameInterested.IsZero() {
509                 cn.priorInterest += time.Since(cn.lastBecameInterested)
510         }
511         cn.updateExpectingChunks()
512         // log.Printf("%p: setting interest: %v", cn, interested)
513         return cn.writeInterested(interested)
514 }
515
516 func (pc *PeerConn) writeInterested(interested bool) bool {
517         return pc.write(pp.Message{
518                 Type: func() pp.MessageType {
519                         if interested {
520                                 return pp.Interested
521                         } else {
522                                 return pp.NotInterested
523                         }
524                 }(),
525         })
526 }
527
528 // The function takes a message to be sent, and returns true if more messages
529 // are okay.
530 type messageWriter func(pp.Message) bool
531
532 func (cn *Peer) request(r Request) (more bool, err error) {
533         if _, ok := cn.requests[r]; ok {
534                 return true, nil
535         }
536         if !cn.peerHasPiece(pieceIndex(r.Index)) {
537                 return true, errors.New("requesting piece peer doesn't have")
538         }
539         if !cn.t.peerIsActive(cn) {
540                 panic("requesting but not in active conns")
541         }
542         if cn.closed.IsSet() {
543                 panic("requesting when connection is closed")
544         }
545         if cn.peerChoking {
546                 if cn.peerAllowedFast.Get(int(r.Index)) {
547                         torrent.Add("allowed fast requests sent", 1)
548                 } else {
549                         return cn.setInterested(true), errors.New("requesting while choked and not allowed fast")
550                 }
551         }
552         if cn.t.hashingPiece(pieceIndex(r.Index)) {
553                 panic("piece is being hashed")
554         }
555         if cn.t.pieceQueuedForHash(pieceIndex(r.Index)) {
556                 panic("piece is queued for hash")
557         }
558         if cn.requests == nil {
559                 cn.requests = make(map[Request]struct{})
560         }
561         cn.requests[r] = struct{}{}
562         if cn.validReceiveChunks == nil {
563                 cn.validReceiveChunks = make(map[Request]int)
564         }
565         cn.validReceiveChunks[r]++
566         cn.t.pendingRequests[r]++
567         cn.updateExpectingChunks()
568         for _, f := range cn.callbacks.SentRequest {
569                 f(PeerRequestEvent{cn, r})
570         }
571         return cn.peerImpl.request(r), nil
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 *PeerConn) fillWriteBuffer() {
588         if cn.pex.IsEnabled() {
589                 if flow := cn.pex.Share(cn.write); !flow {
590                         return
591                 }
592         }
593         cn.upload(cn.write)
594 }
595
596 // Routine that writes to the peer. Some of what to write is buffered by
597 // activity elsewhere in the Client, and some is determined locally when the
598 // connection is writable.
599 func (cn *PeerConn) writer(keepAliveTimeout time.Duration) {
600         var (
601                 lastWrite      time.Time = time.Now()
602                 keepAliveTimer *time.Timer
603         )
604         keepAliveTimer = time.AfterFunc(keepAliveTimeout, func() {
605                 cn.locker().Lock()
606                 defer cn.locker().Unlock()
607                 if time.Since(lastWrite) >= keepAliveTimeout {
608                         cn.tickleWriter()
609                 }
610                 keepAliveTimer.Reset(keepAliveTimeout)
611         })
612         cn.locker().Lock()
613         defer cn.locker().Unlock()
614         defer cn.close()
615         defer keepAliveTimer.Stop()
616         frontBuf := new(bytes.Buffer)
617         for {
618                 if cn.closed.IsSet() {
619                         return
620                 }
621                 if cn.writeBuffer.Len() == 0 {
622                         cn.fillWriteBuffer()
623                 }
624                 if cn.writeBuffer.Len() == 0 && time.Since(lastWrite) >= keepAliveTimeout && cn.useful() {
625                         cn.writeBuffer.Write(pp.Message{Keepalive: true}.MustMarshalBinary())
626                         torrent.Add("written keepalives", 1)
627                 }
628                 if cn.writeBuffer.Len() == 0 {
629                         // TODO: Minimize wakeups....
630                         cn.writerCond.Wait()
631                         continue
632                 }
633                 // Flip the buffers.
634                 frontBuf, cn.writeBuffer = cn.writeBuffer, frontBuf
635                 cn.locker().Unlock()
636                 n, err := cn.w.Write(frontBuf.Bytes())
637                 cn.locker().Lock()
638                 if n != 0 {
639                         lastWrite = time.Now()
640                         keepAliveTimer.Reset(keepAliveTimeout)
641                 }
642                 if err != nil {
643                         cn.logger.WithDefaultLevel(log.Debug).Printf("error writing: %v", err)
644                         return
645                 }
646                 if n != frontBuf.Len() {
647                         panic("short write")
648                 }
649                 frontBuf.Reset()
650         }
651 }
652
653 func (cn *PeerConn) have(piece pieceIndex) {
654         if cn.sentHaves.Get(bitmap.BitIndex(piece)) {
655                 return
656         }
657         cn.post(pp.Message{
658                 Type:  pp.Have,
659                 Index: pp.Integer(piece),
660         })
661         cn.sentHaves.Add(bitmap.BitIndex(piece))
662 }
663
664 func (cn *PeerConn) postBitfield() {
665         if cn.sentHaves.Len() != 0 {
666                 panic("bitfield must be first have-related message sent")
667         }
668         if !cn.t.haveAnyPieces() {
669                 return
670         }
671         cn.post(pp.Message{
672                 Type:     pp.Bitfield,
673                 Bitfield: cn.t.bitfield(),
674         })
675         cn.sentHaves = cn.t._completedPieces.Copy()
676 }
677
678 func (cn *PeerConn) updateRequests() {
679         // log.Print("update requests")
680         cn.tickleWriter()
681 }
682
683 // Emits the indices in the Bitmaps bms in order, never repeating any index.
684 // skip is mutated during execution, and its initial values will never be
685 // emitted.
686 func iterBitmapsDistinct(skip *bitmap.Bitmap, bms ...bitmap.Bitmap) iter.Func {
687         return func(cb iter.Callback) {
688                 for _, bm := range bms {
689                         if !iter.All(
690                                 func(_i interface{}) bool {
691                                         i := _i.(int)
692                                         if skip.Contains(i) {
693                                                 return true
694                                         }
695                                         skip.Add(i)
696                                         return cb(i)
697                                 },
698                                 bm.Iter,
699                         ) {
700                                 return
701                         }
702                 }
703         }
704 }
705
706 // check callers updaterequests
707 func (cn *Peer) stopRequestingPiece(piece pieceIndex) bool {
708         return cn._pieceRequestOrder.Remove(bitmap.BitIndex(piece))
709 }
710
711 // This is distinct from Torrent piece priority, which is the user's
712 // preference. Connection piece priority is specific to a connection and is
713 // used to pseudorandomly avoid connections always requesting the same pieces
714 // and thus wasting effort.
715 func (cn *Peer) updatePiecePriority(piece pieceIndex) bool {
716         tpp := cn.t.piecePriority(piece)
717         if !cn.peerHasPiece(piece) {
718                 tpp = PiecePriorityNone
719         }
720         if tpp == PiecePriorityNone {
721                 return cn.stopRequestingPiece(piece)
722         }
723         prio := cn.getPieceInclination()[piece]
724         return cn._pieceRequestOrder.Set(bitmap.BitIndex(piece), prio)
725 }
726
727 func (cn *Peer) getPieceInclination() []int {
728         if cn.pieceInclination == nil {
729                 cn.pieceInclination = cn.t.getConnPieceInclination()
730         }
731         return cn.pieceInclination
732 }
733
734 func (cn *Peer) discardPieceInclination() {
735         if cn.pieceInclination == nil {
736                 return
737         }
738         cn.t.putPieceInclination(cn.pieceInclination)
739         cn.pieceInclination = nil
740 }
741
742 func (cn *PeerConn) peerPiecesChanged() {
743         if cn.t.haveInfo() {
744                 prioritiesChanged := false
745                 for i := pieceIndex(0); i < cn.t.numPieces(); i++ {
746                         if cn.updatePiecePriority(i) {
747                                 prioritiesChanged = true
748                         }
749                 }
750                 if prioritiesChanged {
751                         cn.updateRequests()
752                 }
753         }
754         cn.t.maybeDropMutuallyCompletePeer(&cn.Peer)
755 }
756
757 func (cn *PeerConn) raisePeerMinPieces(newMin pieceIndex) {
758         if newMin > cn.peerMinPieces {
759                 cn.peerMinPieces = newMin
760         }
761 }
762
763 func (cn *PeerConn) peerSentHave(piece pieceIndex) error {
764         if cn.t.haveInfo() && piece >= cn.t.numPieces() || piece < 0 {
765                 return errors.New("invalid piece")
766         }
767         if cn.peerHasPiece(piece) {
768                 return nil
769         }
770         cn.raisePeerMinPieces(piece + 1)
771         cn._peerPieces.Set(bitmap.BitIndex(piece), true)
772         cn.t.maybeDropMutuallyCompletePeer(&cn.Peer)
773         if cn.updatePiecePriority(piece) {
774                 cn.updateRequests()
775         }
776         return nil
777 }
778
779 func (cn *PeerConn) peerSentBitfield(bf []bool) error {
780         cn.peerSentHaveAll = false
781         if len(bf)%8 != 0 {
782                 panic("expected bitfield length divisible by 8")
783         }
784         // We know that the last byte means that at most the last 7 bits are
785         // wasted.
786         cn.raisePeerMinPieces(pieceIndex(len(bf) - 7))
787         if cn.t.haveInfo() && len(bf) > int(cn.t.numPieces()) {
788                 // Ignore known excess pieces.
789                 bf = bf[:cn.t.numPieces()]
790         }
791         for i, have := range bf {
792                 if have {
793                         cn.raisePeerMinPieces(pieceIndex(i) + 1)
794                 }
795                 cn._peerPieces.Set(i, have)
796         }
797         cn.peerPiecesChanged()
798         return nil
799 }
800
801 func (cn *PeerConn) onPeerSentHaveAll() error {
802         cn.peerSentHaveAll = true
803         cn._peerPieces.Clear()
804         cn.peerPiecesChanged()
805         return nil
806 }
807
808 func (cn *PeerConn) peerSentHaveNone() error {
809         cn._peerPieces.Clear()
810         cn.peerSentHaveAll = false
811         cn.peerPiecesChanged()
812         return nil
813 }
814
815 func (c *PeerConn) requestPendingMetadata() {
816         if c.t.haveInfo() {
817                 return
818         }
819         if c.PeerExtensionIDs[pp.ExtensionNameMetadata] == 0 {
820                 // Peer doesn't support this.
821                 return
822         }
823         // Request metadata pieces that we don't have in a random order.
824         var pending []int
825         for index := 0; index < c.t.metadataPieceCount(); index++ {
826                 if !c.t.haveMetadataPiece(index) && !c.requestedMetadataPiece(index) {
827                         pending = append(pending, index)
828                 }
829         }
830         rand.Shuffle(len(pending), func(i, j int) { pending[i], pending[j] = pending[j], pending[i] })
831         for _, i := range pending {
832                 c.requestMetadataPiece(i)
833         }
834 }
835
836 func (cn *PeerConn) wroteMsg(msg *pp.Message) {
837         torrent.Add(fmt.Sprintf("messages written of type %s", msg.Type.String()), 1)
838         if msg.Type == pp.Extended {
839                 for name, id := range cn.PeerExtensionIDs {
840                         if id != msg.ExtendedID {
841                                 continue
842                         }
843                         torrent.Add(fmt.Sprintf("Extended messages written for protocol %q", name), 1)
844                 }
845         }
846         cn.allStats(func(cs *ConnStats) { cs.wroteMsg(msg) })
847 }
848
849 func (cn *PeerConn) readMsg(msg *pp.Message) {
850         cn.allStats(func(cs *ConnStats) { cs.readMsg(msg) })
851 }
852
853 // After handshake, we know what Torrent and Client stats to include for a
854 // connection.
855 func (cn *Peer) postHandshakeStats(f func(*ConnStats)) {
856         t := cn.t
857         f(&t.stats)
858         f(&t.cl.stats)
859 }
860
861 // All ConnStats that include this connection. Some objects are not known
862 // until the handshake is complete, after which it's expected to reconcile the
863 // differences.
864 func (cn *Peer) allStats(f func(*ConnStats)) {
865         f(&cn._stats)
866         if cn.reconciledHandshakeStats {
867                 cn.postHandshakeStats(f)
868         }
869 }
870
871 func (cn *PeerConn) wroteBytes(n int64) {
872         cn.allStats(add(n, func(cs *ConnStats) *Count { return &cs.BytesWritten }))
873 }
874
875 func (cn *PeerConn) readBytes(n int64) {
876         cn.allStats(add(n, func(cs *ConnStats) *Count { return &cs.BytesRead }))
877 }
878
879 // Returns whether the connection could be useful to us. We're seeding and
880 // they want data, we don't have metainfo and they can provide it, etc.
881 func (c *Peer) useful() bool {
882         t := c.t
883         if c.closed.IsSet() {
884                 return false
885         }
886         if !t.haveInfo() {
887                 return c.supportsExtension("ut_metadata")
888         }
889         if t.seeding() && c.peerInterested {
890                 return true
891         }
892         if c.peerHasWantedPieces() {
893                 return true
894         }
895         return false
896 }
897
898 func (c *Peer) lastHelpful() (ret time.Time) {
899         ret = c.lastUsefulChunkReceived
900         if c.t.seeding() && c.lastChunkSent.After(ret) {
901                 ret = c.lastChunkSent
902         }
903         return
904 }
905
906 func (c *PeerConn) fastEnabled() bool {
907         return c.PeerExtensionBytes.SupportsFast() && c.t.cl.config.Extensions.SupportsFast()
908 }
909
910 func (c *PeerConn) reject(r Request) {
911         if !c.fastEnabled() {
912                 panic("fast not enabled")
913         }
914         c.post(r.ToMsg(pp.Reject))
915         delete(c.peerRequests, r)
916 }
917
918 func (c *PeerConn) onReadRequest(r Request) error {
919         requestedChunkLengths.Add(strconv.FormatUint(r.Length.Uint64(), 10), 1)
920         if _, ok := c.peerRequests[r]; ok {
921                 torrent.Add("duplicate requests received", 1)
922                 return nil
923         }
924         if c.choking {
925                 torrent.Add("requests received while choking", 1)
926                 if c.fastEnabled() {
927                         torrent.Add("requests rejected while choking", 1)
928                         c.reject(r)
929                 }
930                 return nil
931         }
932         if len(c.peerRequests) >= maxRequests {
933                 torrent.Add("requests received while queue full", 1)
934                 if c.fastEnabled() {
935                         c.reject(r)
936                 }
937                 // BEP 6 says we may close here if we choose.
938                 return nil
939         }
940         if !c.t.havePiece(pieceIndex(r.Index)) {
941                 // This isn't necessarily them screwing up. We can drop pieces
942                 // from our storage, and can't communicate this to peers
943                 // except by reconnecting.
944                 requestsReceivedForMissingPieces.Add(1)
945                 return fmt.Errorf("peer requested piece we don't have: %v", r.Index.Int())
946         }
947         // Check this after we know we have the piece, so that the piece length will be known.
948         if r.Begin+r.Length > c.t.pieceLength(pieceIndex(r.Index)) {
949                 torrent.Add("bad requests received", 1)
950                 return errors.New("bad Request")
951         }
952         if c.peerRequests == nil {
953                 c.peerRequests = make(map[Request]*peerRequestState, maxRequests)
954         }
955         value := &peerRequestState{}
956         c.peerRequests[r] = value
957         go c.peerRequestDataReader(r, value)
958         //c.tickleWriter()
959         return nil
960 }
961
962 func (c *PeerConn) peerRequestDataReader(r Request, prs *peerRequestState) {
963         b, err := readPeerRequestData(r, c)
964         c.locker().Lock()
965         defer c.locker().Unlock()
966         if err != nil {
967                 c.peerRequestDataReadFailed(err, r)
968         } else {
969                 if b == nil {
970                         panic("data must be non-nil to trigger send")
971                 }
972                 prs.data = b
973                 c.tickleWriter()
974         }
975 }
976
977 // If this is maintained correctly, we might be able to support optional synchronous reading for
978 // chunk sending, the way it used to work.
979 func (c *PeerConn) peerRequestDataReadFailed(err error, r Request) {
980         c.logger.WithDefaultLevel(log.Warning).Printf("error reading chunk for peer Request %v: %v", r, err)
981         i := pieceIndex(r.Index)
982         if c.t.pieceComplete(i) {
983                 // There used to be more code here that just duplicated the following break. Piece
984                 // completions are currently cached, so I'm not sure how helpful this update is, except to
985                 // pull any completion changes pushed to the storage backend in failed reads that got us
986                 // here.
987                 c.t.updatePieceCompletion(i)
988         }
989         // If we failed to send a chunk, choke the peer to ensure they flush all their requests. We've
990         // probably dropped a piece from storage, but there's no way to communicate this to the peer. If
991         // they ask for it again, we'll kick them to allow us to send them an updated bitfield on the
992         // next connect. TODO: Support rejecting here too.
993         if c.choking {
994                 c.logger.WithDefaultLevel(log.Warning).Printf("already choking peer, requests might not be rejected correctly")
995         }
996         c.choke(c.post)
997 }
998
999 func readPeerRequestData(r Request, c *PeerConn) ([]byte, error) {
1000         b := make([]byte, r.Length)
1001         p := c.t.info.Piece(int(r.Index))
1002         n, err := c.t.readAt(b, p.Offset()+int64(r.Begin))
1003         if n == len(b) {
1004                 if err == io.EOF {
1005                         err = nil
1006                 }
1007         } else {
1008                 if err == nil {
1009                         panic("expected error")
1010                 }
1011         }
1012         return b, err
1013 }
1014
1015 func runSafeExtraneous(f func()) {
1016         if true {
1017                 go f()
1018         } else {
1019                 f()
1020         }
1021 }
1022
1023 // Processes incoming BitTorrent wire-protocol messages. The client lock is held upon entry and
1024 // exit. Returning will end the connection.
1025 func (c *PeerConn) mainReadLoop() (err error) {
1026         defer func() {
1027                 if err != nil {
1028                         torrent.Add("connection.mainReadLoop returned with error", 1)
1029                 } else {
1030                         torrent.Add("connection.mainReadLoop returned with no error", 1)
1031                 }
1032         }()
1033         t := c.t
1034         cl := t.cl
1035
1036         decoder := pp.Decoder{
1037                 R:         bufio.NewReaderSize(c.r, 1<<17),
1038                 MaxLength: 256 * 1024,
1039                 Pool:      t.chunkPool,
1040         }
1041         for {
1042                 var msg pp.Message
1043                 func() {
1044                         cl.unlock()
1045                         defer cl.lock()
1046                         err = decoder.Decode(&msg)
1047                 }()
1048                 if cb := c.callbacks.ReadMessage; cb != nil && err == nil {
1049                         cb(c, &msg)
1050                 }
1051                 if t.closed.IsSet() || c.closed.IsSet() {
1052                         return nil
1053                 }
1054                 if err != nil {
1055                         return err
1056                 }
1057                 c.readMsg(&msg)
1058                 c.lastMessageReceived = time.Now()
1059                 if msg.Keepalive {
1060                         receivedKeepalives.Add(1)
1061                         continue
1062                 }
1063                 messageTypesReceived.Add(msg.Type.String(), 1)
1064                 if msg.Type.FastExtension() && !c.fastEnabled() {
1065                         runSafeExtraneous(func() { torrent.Add("fast messages received when extension is disabled", 1) })
1066                         return fmt.Errorf("received fast extension message (type=%v) but extension is disabled", msg.Type)
1067                 }
1068                 switch msg.Type {
1069                 case pp.Choke:
1070                         c.peerChoking = true
1071                         if !c.fastEnabled() {
1072                                 c.deleteAllRequests()
1073                         }
1074                         // We can then reset our interest.
1075                         c.updateRequests()
1076                         c.updateExpectingChunks()
1077                 case pp.Unchoke:
1078                         c.peerChoking = false
1079                         c.tickleWriter()
1080                         c.updateExpectingChunks()
1081                 case pp.Interested:
1082                         c.peerInterested = true
1083                         c.tickleWriter()
1084                 case pp.NotInterested:
1085                         c.peerInterested = false
1086                         // We don't clear their requests since it isn't clear in the spec.
1087                         // We'll probably choke them for this, which will clear them if
1088                         // appropriate, and is clearly specified.
1089                 case pp.Have:
1090                         err = c.peerSentHave(pieceIndex(msg.Index))
1091                 case pp.Bitfield:
1092                         err = c.peerSentBitfield(msg.Bitfield)
1093                 case pp.Request:
1094                         r := newRequestFromMessage(&msg)
1095                         err = c.onReadRequest(r)
1096                 case pp.Piece:
1097                         err = c.receiveChunk(&msg)
1098                         if len(msg.Piece) == int(t.chunkSize) {
1099                                 t.chunkPool.Put(&msg.Piece)
1100                         }
1101                         if err != nil {
1102                                 err = fmt.Errorf("receiving chunk: %s", err)
1103                         }
1104                 case pp.Cancel:
1105                         req := newRequestFromMessage(&msg)
1106                         c.onPeerSentCancel(req)
1107                 case pp.Port:
1108                         ipa, ok := tryIpPortFromNetAddr(c.RemoteAddr)
1109                         if !ok {
1110                                 break
1111                         }
1112                         pingAddr := net.UDPAddr{
1113                                 IP:   ipa.IP,
1114                                 Port: ipa.Port,
1115                         }
1116                         if msg.Port != 0 {
1117                                 pingAddr.Port = int(msg.Port)
1118                         }
1119                         cl.eachDhtServer(func(s DhtServer) {
1120                                 go s.Ping(&pingAddr)
1121                         })
1122                 case pp.Suggest:
1123                         torrent.Add("suggests received", 1)
1124                         log.Fmsg("peer suggested piece %d", msg.Index).AddValues(c, msg.Index).SetLevel(log.Debug).Log(c.t.logger)
1125                         c.updateRequests()
1126                 case pp.HaveAll:
1127                         err = c.onPeerSentHaveAll()
1128                 case pp.HaveNone:
1129                         err = c.peerSentHaveNone()
1130                 case pp.Reject:
1131                         c.remoteRejectedRequest(newRequestFromMessage(&msg))
1132                 case pp.AllowedFast:
1133                         torrent.Add("allowed fasts received", 1)
1134                         log.Fmsg("peer allowed fast: %d", msg.Index).AddValues(c).SetLevel(log.Debug).Log(c.t.logger)
1135                         c.peerAllowedFast.Add(int(msg.Index))
1136                         c.updateRequests()
1137                 case pp.Extended:
1138                         err = c.onReadExtendedMsg(msg.ExtendedID, msg.ExtendedPayload)
1139                 default:
1140                         err = fmt.Errorf("received unknown message type: %#v", msg.Type)
1141                 }
1142                 if err != nil {
1143                         return err
1144                 }
1145         }
1146 }
1147
1148 func (c *Peer) remoteRejectedRequest(r Request) {
1149         if c.deleteRequest(r) {
1150                 c.decExpectedChunkReceive(r)
1151         }
1152 }
1153
1154 func (c *Peer) decExpectedChunkReceive(r Request) {
1155         count := c.validReceiveChunks[r]
1156         if count == 1 {
1157                 delete(c.validReceiveChunks, r)
1158         } else if count > 1 {
1159                 c.validReceiveChunks[r] = count - 1
1160         } else {
1161                 panic(r)
1162         }
1163 }
1164
1165 func (c *PeerConn) onReadExtendedMsg(id pp.ExtensionNumber, payload []byte) (err error) {
1166         defer func() {
1167                 // TODO: Should we still do this?
1168                 if err != nil {
1169                         // These clients use their own extension IDs for outgoing message
1170                         // types, which is incorrect.
1171                         if bytes.HasPrefix(c.PeerID[:], []byte("-SD0100-")) || strings.HasPrefix(string(c.PeerID[:]), "-XL0012-") {
1172                                 err = nil
1173                         }
1174                 }
1175         }()
1176         t := c.t
1177         cl := t.cl
1178         switch id {
1179         case pp.HandshakeExtendedID:
1180                 var d pp.ExtendedHandshakeMessage
1181                 if err := bencode.Unmarshal(payload, &d); err != nil {
1182                         c.logger.Printf("error parsing extended handshake message %q: %s", payload, err)
1183                         return fmt.Errorf("unmarshalling extended handshake payload: %w", err)
1184                 }
1185                 if cb := c.callbacks.ReadExtendedHandshake; cb != nil {
1186                         cb(c, &d)
1187                 }
1188                 //c.logger.WithDefaultLevel(log.Debug).Printf("received extended handshake message:\n%s", spew.Sdump(d))
1189                 if d.Reqq != 0 {
1190                         c.PeerMaxRequests = d.Reqq
1191                 }
1192                 c.PeerClientName = d.V
1193                 if c.PeerExtensionIDs == nil {
1194                         c.PeerExtensionIDs = make(map[pp.ExtensionName]pp.ExtensionNumber, len(d.M))
1195                 }
1196                 c.PeerListenPort = d.Port
1197                 c.PeerPrefersEncryption = d.Encryption
1198                 for name, id := range d.M {
1199                         if _, ok := c.PeerExtensionIDs[name]; !ok {
1200                                 peersSupportingExtension.Add(string(name), 1)
1201                         }
1202                         c.PeerExtensionIDs[name] = id
1203                 }
1204                 if d.MetadataSize != 0 {
1205                         if err = t.setMetadataSize(d.MetadataSize); err != nil {
1206                                 return fmt.Errorf("setting metadata size to %d: %w", d.MetadataSize, err)
1207                         }
1208                 }
1209                 c.requestPendingMetadata()
1210                 if !t.cl.config.DisablePEX {
1211                         t.pex.Add(c) // we learnt enough now
1212                         c.pex.Init(c)
1213                 }
1214                 return nil
1215         case metadataExtendedId:
1216                 err := cl.gotMetadataExtensionMsg(payload, t, c)
1217                 if err != nil {
1218                         return fmt.Errorf("handling metadata extension message: %w", err)
1219                 }
1220                 return nil
1221         case pexExtendedId:
1222                 if !c.pex.IsEnabled() {
1223                         return nil // or hang-up maybe?
1224                 }
1225                 return c.pex.Recv(payload)
1226         default:
1227                 return fmt.Errorf("unexpected extended message ID: %v", id)
1228         }
1229 }
1230
1231 // Set both the Reader and Writer for the connection from a single ReadWriter.
1232 func (cn *PeerConn) setRW(rw io.ReadWriter) {
1233         cn.r = rw
1234         cn.w = rw
1235 }
1236
1237 // Returns the Reader and Writer as a combined ReadWriter.
1238 func (cn *PeerConn) rw() io.ReadWriter {
1239         return struct {
1240                 io.Reader
1241                 io.Writer
1242         }{cn.r, cn.w}
1243 }
1244
1245 // Handle a received chunk from a peer.
1246 func (c *Peer) receiveChunk(msg *pp.Message) error {
1247         t := c.t
1248         cl := t.cl
1249         chunksReceived.Add("total", 1)
1250
1251         req := newRequestFromMessage(msg)
1252
1253         if c.peerChoking {
1254                 chunksReceived.Add("while choked", 1)
1255         }
1256
1257         if c.validReceiveChunks[req] <= 0 {
1258                 chunksReceived.Add("unexpected", 1)
1259                 return errors.New("received unexpected chunk")
1260         }
1261         c.decExpectedChunkReceive(req)
1262
1263         if c.peerChoking && c.peerAllowedFast.Get(int(req.Index)) {
1264                 chunksReceived.Add("due to allowed fast", 1)
1265         }
1266
1267         // TODO: This needs to happen immediately, to prevent cancels occurring asynchronously when have
1268         // actually already received the piece, while we have the Client unlocked to write the data out.
1269         {
1270                 if _, ok := c.requests[req]; ok {
1271                         for _, f := range c.callbacks.ReceivedRequested {
1272                                 f(PeerMessageEvent{c, msg})
1273                         }
1274                 }
1275                 // Request has been satisfied.
1276                 if c.deleteRequest(req) {
1277                         if c.expectingChunks() {
1278                                 c._chunksReceivedWhileExpecting++
1279                         }
1280                 } else {
1281                         chunksReceived.Add("unwanted", 1)
1282                 }
1283         }
1284
1285         // Do we actually want this chunk?
1286         if t.haveChunk(req) {
1287                 chunksReceived.Add("wasted", 1)
1288                 c.allStats(add(1, func(cs *ConnStats) *Count { return &cs.ChunksReadWasted }))
1289                 return nil
1290         }
1291
1292         piece := &t.pieces[req.Index]
1293
1294         c.allStats(add(1, func(cs *ConnStats) *Count { return &cs.ChunksReadUseful }))
1295         c.allStats(add(int64(len(msg.Piece)), func(cs *ConnStats) *Count { return &cs.BytesReadUsefulData }))
1296         for _, f := range c.t.cl.config.Callbacks.ReceivedUsefulData {
1297                 f(ReceivedUsefulDataEvent{c, msg})
1298         }
1299         c.lastUsefulChunkReceived = time.Now()
1300         // if t.fastestPeer != c {
1301         // log.Printf("setting fastest connection %p", c)
1302         // }
1303         t.fastestPeer = c
1304
1305         // Need to record that it hasn't been written yet, before we attempt to do
1306         // anything with it.
1307         piece.incrementPendingWrites()
1308         // Record that we have the chunk, so we aren't trying to download it while
1309         // waiting for it to be written to storage.
1310         piece.unpendChunkIndex(chunkIndex(req.ChunkSpec, t.chunkSize))
1311
1312         // Cancel pending requests for this chunk from *other* peers.
1313         t.iterPeers(func(p *Peer) {
1314                 if p == c {
1315                         return
1316                 }
1317                 p.postCancel(req)
1318         })
1319
1320         err := func() error {
1321                 cl.unlock()
1322                 defer cl.lock()
1323                 concurrentChunkWrites.Add(1)
1324                 defer concurrentChunkWrites.Add(-1)
1325                 // Write the chunk out. Note that the upper bound on chunk writing concurrency will be the
1326                 // number of connections. We write inline with receiving the chunk (with this lock dance),
1327                 // because we want to handle errors synchronously and I haven't thought of a nice way to
1328                 // defer any concurrency to the storage and have that notify the client of errors. TODO: Do
1329                 // that instead.
1330                 return t.writeChunk(int(msg.Index), int64(msg.Begin), msg.Piece)
1331         }()
1332
1333         piece.decrementPendingWrites()
1334
1335         if err != nil {
1336                 c.logger.WithDefaultLevel(log.Error).Printf("writing received chunk %v: %v", req, err)
1337                 t.pendRequest(req)
1338                 //t.updatePieceCompletion(pieceIndex(msg.Index))
1339                 t.onWriteChunkErr(err)
1340                 return nil
1341         }
1342
1343         c.onDirtiedPiece(pieceIndex(req.Index))
1344
1345         // We need to ensure the piece is only queued once, so only the last chunk writer gets this job.
1346         if t.pieceAllDirty(pieceIndex(req.Index)) && piece.pendingWrites == 0 {
1347                 t.queuePieceCheck(pieceIndex(req.Index))
1348                 // We don't pend all chunks here anymore because we don't want code dependent on the dirty
1349                 // chunk status (such as the haveChunk call above) to have to check all the various other
1350                 // piece states like queued for hash, hashing etc. This does mean that we need to be sure
1351                 // that chunk pieces are pended at an appropriate time later however.
1352         }
1353
1354         cl.event.Broadcast()
1355         // We do this because we've written a chunk, and may change PieceState.Partial.
1356         t.publishPieceChange(pieceIndex(req.Index))
1357
1358         return nil
1359 }
1360
1361 func (c *Peer) onDirtiedPiece(piece pieceIndex) {
1362         if c.peerTouchedPieces == nil {
1363                 c.peerTouchedPieces = make(map[pieceIndex]struct{})
1364         }
1365         c.peerTouchedPieces[piece] = struct{}{}
1366         ds := &c.t.pieces[piece].dirtiers
1367         if *ds == nil {
1368                 *ds = make(map[*Peer]struct{})
1369         }
1370         (*ds)[c] = struct{}{}
1371 }
1372
1373 func (c *PeerConn) uploadAllowed() bool {
1374         if c.t.cl.config.NoUpload {
1375                 return false
1376         }
1377         if c.t.dataUploadDisallowed {
1378                 return false
1379         }
1380         if c.t.seeding() {
1381                 return true
1382         }
1383         if !c.peerHasWantedPieces() {
1384                 return false
1385         }
1386         // Don't upload more than 100 KiB more than we download.
1387         if c._stats.BytesWrittenData.Int64() >= c._stats.BytesReadData.Int64()+100<<10 {
1388                 return false
1389         }
1390         return true
1391 }
1392
1393 func (c *PeerConn) setRetryUploadTimer(delay time.Duration) {
1394         if c.uploadTimer == nil {
1395                 c.uploadTimer = time.AfterFunc(delay, c.writerCond.Broadcast)
1396         } else {
1397                 c.uploadTimer.Reset(delay)
1398         }
1399 }
1400
1401 // Also handles choking and unchoking of the remote peer.
1402 func (c *PeerConn) upload(msg func(pp.Message) bool) bool {
1403         // Breaking or completing this loop means we don't want to upload to the
1404         // peer anymore, and we choke them.
1405 another:
1406         for c.uploadAllowed() {
1407                 // We want to upload to the peer.
1408                 if !c.unchoke(msg) {
1409                         return false
1410                 }
1411                 for r, state := range c.peerRequests {
1412                         if state.data == nil {
1413                                 continue
1414                         }
1415                         res := c.t.cl.config.UploadRateLimiter.ReserveN(time.Now(), int(r.Length))
1416                         if !res.OK() {
1417                                 panic(fmt.Sprintf("upload rate limiter burst size < %d", r.Length))
1418                         }
1419                         delay := res.Delay()
1420                         if delay > 0 {
1421                                 res.Cancel()
1422                                 c.setRetryUploadTimer(delay)
1423                                 // Hard to say what to return here.
1424                                 return true
1425                         }
1426                         more := c.sendChunk(r, msg, state)
1427                         delete(c.peerRequests, r)
1428                         if !more {
1429                                 return false
1430                         }
1431                         goto another
1432                 }
1433                 return true
1434         }
1435         return c.choke(msg)
1436 }
1437
1438 func (cn *PeerConn) drop() {
1439         cn.t.dropConnection(cn)
1440 }
1441
1442 func (cn *Peer) netGoodPiecesDirtied() int64 {
1443         return cn._stats.PiecesDirtiedGood.Int64() - cn._stats.PiecesDirtiedBad.Int64()
1444 }
1445
1446 func (c *Peer) peerHasWantedPieces() bool {
1447         return !c._pieceRequestOrder.IsEmpty()
1448 }
1449
1450 func (c *Peer) numLocalRequests() int {
1451         return len(c.requests)
1452 }
1453
1454 func (c *Peer) deleteRequest(r Request) bool {
1455         if _, ok := c.requests[r]; !ok {
1456                 return false
1457         }
1458         delete(c.requests, r)
1459         for _, f := range c.callbacks.DeletedRequest {
1460                 f(PeerRequestEvent{c, r})
1461         }
1462         c.updateExpectingChunks()
1463         pr := c.t.pendingRequests
1464         pr[r]--
1465         n := pr[r]
1466         if n == 0 {
1467                 delete(pr, r)
1468         }
1469         if n < 0 {
1470                 panic(n)
1471         }
1472         // If a request fails, updating the requests for the current peer first may miss the opportunity
1473         // to try other peers for that request instead, depending on the request strategy. This might
1474         // only affect webseed peers though, since they synchronously issue new requests: PeerConns do
1475         // it in the writer routine.
1476         const updateCurrentConnRequestsFirst = false
1477         if updateCurrentConnRequestsFirst {
1478                 c.updateRequests()
1479         }
1480         // Give other conns a chance to pick up the request.
1481         c.t.iterPeers(func(_c *Peer) {
1482                 // We previously checked that the peer wasn't interested to to only wake connections that
1483                 // were unable to issue requests due to starvation by the request strategy. There could be
1484                 // performance ramifications.
1485                 if _c != c && c.peerHasPiece(pieceIndex(r.Index)) {
1486                         _c.updateRequests()
1487                 }
1488         })
1489         if !updateCurrentConnRequestsFirst {
1490                 c.updateRequests()
1491         }
1492         return true
1493 }
1494
1495 func (c *Peer) deleteAllRequests() {
1496         for r := range c.requests {
1497                 c.deleteRequest(r)
1498         }
1499         if len(c.requests) != 0 {
1500                 panic(len(c.requests))
1501         }
1502         // for c := range c.t.conns {
1503         //      c.tickleWriter()
1504         // }
1505 }
1506
1507 // This is called when something has changed that should wake the writer, such as putting stuff into
1508 // the writeBuffer, or changing some state that the writer can act on.
1509 func (c *PeerConn) tickleWriter() {
1510         c.writerCond.Broadcast()
1511 }
1512
1513 func (c *Peer) postCancel(r Request) bool {
1514         if !c.deleteRequest(r) {
1515                 return false
1516         }
1517         c.peerImpl._postCancel(r)
1518         return true
1519 }
1520
1521 func (c *PeerConn) _postCancel(r Request) {
1522         c.post(makeCancelMessage(r))
1523 }
1524
1525 func (c *PeerConn) sendChunk(r Request, msg func(pp.Message) bool, state *peerRequestState) (more bool) {
1526         c.lastChunkSent = time.Now()
1527         return msg(pp.Message{
1528                 Type:  pp.Piece,
1529                 Index: r.Index,
1530                 Begin: r.Begin,
1531                 Piece: state.data,
1532         })
1533 }
1534
1535 func (c *PeerConn) setTorrent(t *Torrent) {
1536         if c.t != nil {
1537                 panic("connection already associated with a torrent")
1538         }
1539         c.t = t
1540         c.logger.WithDefaultLevel(log.Debug).Printf("set torrent=%v", t)
1541         t.reconcileHandshakeStats(c)
1542 }
1543
1544 func (c *Peer) peerPriority() (peerPriority, error) {
1545         return bep40Priority(c.remoteIpPort(), c.t.cl.publicAddr(c.remoteIp()))
1546 }
1547
1548 func (c *Peer) remoteIp() net.IP {
1549         host, _, _ := net.SplitHostPort(c.RemoteAddr.String())
1550         return net.ParseIP(host)
1551 }
1552
1553 func (c *Peer) remoteIpPort() IpPort {
1554         ipa, _ := tryIpPortFromNetAddr(c.RemoteAddr)
1555         return IpPort{ipa.IP, uint16(ipa.Port)}
1556 }
1557
1558 func (c *PeerConn) pexPeerFlags() pp.PexPeerFlags {
1559         f := pp.PexPeerFlags(0)
1560         if c.PeerPrefersEncryption {
1561                 f |= pp.PexPrefersEncryption
1562         }
1563         if c.outgoing {
1564                 f |= pp.PexOutgoingConn
1565         }
1566         if c.utp() {
1567                 f |= pp.PexSupportsUtp
1568         }
1569         return f
1570 }
1571
1572 // This returns the address to use if we want to dial the peer again. It incorporates the peer's
1573 // advertised listen port.
1574 func (c *PeerConn) dialAddr() PeerRemoteAddr {
1575         if !c.outgoing && c.PeerListenPort != 0 {
1576                 switch addr := c.RemoteAddr.(type) {
1577                 case *net.TCPAddr:
1578                         dialAddr := *addr
1579                         dialAddr.Port = c.PeerListenPort
1580                         return &dialAddr
1581                 case *net.UDPAddr:
1582                         dialAddr := *addr
1583                         dialAddr.Port = c.PeerListenPort
1584                         return &dialAddr
1585                 }
1586         }
1587         return c.RemoteAddr
1588 }
1589
1590 func (c *PeerConn) pexEvent(t pexEventType) pexEvent {
1591         f := c.pexPeerFlags()
1592         addr := c.dialAddr()
1593         return pexEvent{t, addr, f}
1594 }
1595
1596 func (c *PeerConn) String() string {
1597         return fmt.Sprintf("connection %p", c)
1598 }
1599
1600 func (c *Peer) trust() connectionTrust {
1601         return connectionTrust{c.trusted, c.netGoodPiecesDirtied()}
1602 }
1603
1604 type connectionTrust struct {
1605         Implicit            bool
1606         NetGoodPiecesDirted int64
1607 }
1608
1609 func (l connectionTrust) Less(r connectionTrust) bool {
1610         return multiless.New().Bool(l.Implicit, r.Implicit).Int64(l.NetGoodPiecesDirted, r.NetGoodPiecesDirted).Less()
1611 }
1612
1613 func (cn *Peer) chunksReceivedWhileExpecting() int64 {
1614         return cn._chunksReceivedWhileExpecting
1615 }
1616
1617 func (cn *Peer) fastest() bool {
1618         return cn == cn.t.fastestPeer
1619 }
1620
1621 func (cn *Peer) peerMaxRequests() int {
1622         return cn.PeerMaxRequests
1623 }
1624
1625 // Returns the pieces the peer has claimed to have.
1626 func (cn *PeerConn) PeerPieces() bitmap.Bitmap {
1627         cn.locker().RLock()
1628         defer cn.locker().RUnlock()
1629         return cn.peerPieces()
1630 }
1631
1632 func (cn *Peer) peerPieces() bitmap.Bitmap {
1633         ret := cn._peerPieces.Copy()
1634         if cn.peerSentHaveAll {
1635                 ret.AddRange(0, cn.t.numPieces())
1636         }
1637         return ret
1638 }
1639
1640 func (cn *Peer) pieceRequestOrder() *prioritybitmap.PriorityBitmap {
1641         return &cn._pieceRequestOrder
1642 }
1643
1644 func (cn *Peer) stats() *ConnStats {
1645         return &cn._stats
1646 }
1647
1648 func (p *Peer) TryAsPeerConn() (*PeerConn, bool) {
1649         pc, ok := p.peerImpl.(*PeerConn)
1650         return pc, ok
1651 }